content
stringlengths
5
1.05M
from enum import Enum import sys import cbor ''' /** Opcodes; encoded in first byte of header. */ #define MGMT_OP_READ 0 #define MGMT_OP_READ_RSP 1 #define MGMT_OP_WRITE 2 #define MGMT_OP_WRITE_RSP 3 ''' class MgmtOp(Enum): READ = 0 READ_RSP = 1 WRITE = 2 ...
""" *Fourier-Coefficients Iterate* Iterate over the fourier coefficients. """ from .._coefficients import FourierCoefficients __all__ = ["FourierCoefficientsIterate"] class FourierCoefficientsIterate: def __next__(self): ... def __iter__(self): return self
# -*- coding: utf-8 -*- import os import pytest from cleo import CommandTester def test_lock(app, mocker): base_dir = os.path.join( os.path.dirname(__file__), '..', '..', 'examples', 'basic' ) lock = os.path.join(base_dir, 'poetry.lock') if os.path.exists(lock): os.unlink(lock) g...
from typing import Type from django.urls import path, include from django.views.generic import TemplateView from rest_framework import routers, permissions from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer from rest_framework_swagger.view...
from otBase import BaseTTXConverter class table_G_P_O_S_(BaseTTXConverter): pass
import os import git import dvc import dvc.repo import numpy as np import subprocess import argparse from dvc.repo import Repo as DVCRepo import networkx as nx import matplotlib.pyplot as plt import numpy as np from dvc.repo import Repo as DVCRepo def rename_stage_names(old_name): # if file is in folder than make ...
import pandas as pd import time import datetime import requests from urllib.request import Request, urlopen import lineTool import linepush import csv from opencc import OpenCC #定義並取得今天和昨天strftime後的日期 td=time.strftime("%Y%m%d") def Yesterday(): today = datetime.date.today() oneday = datetime.timedelta(days=1) ...
from src import db from src.lib.search import add_to_index, remove_from_index, \ query_index, TagsIndex, UsersIndex class SearchableMixin(object): @classmethod def search(cls, indexDoc, expression): ids, total = query_index(indexDoc, expression) if total == 0: return [] ...
_base_ = [ '../_base_/models/fcn_r50-d8.py', '../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py' ] model = dict( decode_head=dict(align_corners=True), auxiliary_head=dict(align_corners=True), test_cfg=dict(mode='slide', crop_s...
def error (x,y) : if y != '(' and y != ')' and y != '0' and y != '1' and y != '*': print ("Недопустимый символ", y) elif x == 0 and y == '(': print ("Ожидался символ (") elif x == 1 and y == ')' : print ("Количество единиц не удовлетворяет условию. Ожидался символ 1") elif x == 1...
import json import logging import os import sys import requests from flask import Flask, request, Response logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) LOG = logging.getLogger('telegram:main') tg_bot_token = os.getenv('TG_BOT_TOKEN') tg_api_base_url = 'https://api.telegram.org/bot' tg_api_url = f'{tg_...
# Copyright 2020 Xilinx 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, ...
#!/usr/bin/env python3 import csv donations = {} with open('raw_donations.csv', 'r') as csvfile: lines = csv.reader(csvfile) for row in lines: fundraiser_in_memory = row[0] amount = float(row[1]) first_name = row[2] last_name = row[3] email = row[4] # we want ...
# -*- coding: utf-8 -*- # Copyright (c) 2014, Joshua Stone # 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 notice, this # li...
from cltk.stem.latin.stem import Stemmer from flask_restful import Resource class Stem(Resource): """ GET /core/stem/<string:sentence> Takes sentence input and strips suffix using CLTK's core Stemmer """ def get(self, sentence): stemmer = Stemmer() return {'stemmed_outp...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from multiprocessing import Queue from . fetchsymbol import FetchSymbol from . basestock import BaseStock from constant.stock import RetriveType, Info # URL for List & OTC company DICT_CRAWL_CODE_URL = { "STR_LISTED_COMPANY": "http://isin.twse.com.tw/isin/C_public.jsp...
#!/usr/bin/env python # coding=utf-8 ''' Author:Tai Lei Date: Info: ''' import random import numpy as np import rospkg from lxml import etree from lxml.etree import Element from copy import deepcopy import yaml rospack = rospkg.RosPack() with open(rospack.get_path("actor_services")+"/src/multiforceFactors.yaml", 'r'...
# encoding: 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 'MacDB' db.create_table('switch_macdb', ( ('id', self.gf('django.db.models.fiel...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from . lm import LM from . torch_utils import get_known_length_canvas, sample_permutation, seq_cross_entropy, collect, batch_randint, select from vocab import Vocab class LBLM(LM): """Length-aware Blank Language Model""" d...
from .singleton_widgets import *
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import logging import os from collections import defaultdict from fvcore.common.file_io import PathManager import json import torch logger = logging.getLogger(__name__) # FPS = 30 # AVA_VALID_FRAMES = range(902, 1799) de...
# Generated by Django 3.1.7 on 2021-03-29 10:50 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0016_auto_20210319_1536'), ] operations = [ migrations.AddField( model_name='custo...
import re from typing import TypedDict,Callable,Optional,Tuple,List,Any,Dict from enum import Enum from datetime import date import asyncio import aio_pika import cbor import socket import struct import aioredis import zmq import zmq.asyncio import uuid import etcd3 import redis class ConnectionLocatorProperties(Type...
from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=250) slug= models.SlugField(max_length=250) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = model...
'''OpenGL extension SGIX.igloo_interface This module customises the behaviour of the OpenGL.raw.GL.SGIX.igloo_interface to provide a more Python-friendly API The official definition of this extension is available here: http://www.opengl.org/registry/specs/SGIX/igloo_interface.txt ''' from OpenGL import platform, co...
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import argparse import logging import re import time import sys from collections import defaultdict from copy import copy from datetime import datetime, timedelta from func...
# # SPDX-License-Identifier: BSD-2-Clause # Copyright 2013-2021, John McNamara, jmcnamara@cpan.org # __version__ = '3.0.2' __VERSION__ = __version__ from .workbook import Workbook
from flask_mail import Message from mailer import mailer from middleware.error_handling import write_log class MailService: @staticmethod def send_welcome_email(email: str, full_name: str) -> None: try: email = Message( subject="Welcome to DNSTool!", recipie...
import dramatiq import os import transaction from dramatiq.rate_limits import ConcurrentRateLimiter from dramatiq.rate_limits.backends import RedisBackend from elasticsearch_dsl import connections from pyramid.paster import get_appsettings, setup_logging from threading import local from toja.models import get_engine,...
import os from constants import DATA_DIR, DATASETS_DIR, TFREC_DIR from datasets import download_and_convert_stl10 for dir in [DATA_DIR, DATASETS_DIR, TFREC_DIR]: if not os.path.exists(dir): os.mkdir(dir) download_and_convert_stl10.run()
import re import sys from pathlib import Path import matplotlib.pyplot as plt import pandas as pd # export CUDA_VISIBLE_DEVICES=0; nohup python -u train.py --use_lstm --batch_size 256 --task char > lstm.log 2>&1 & # export CUDA_VISIBLE_DEVICES=1; nohup python -u train.py --batch_size 256 --task char > tcn.log 2>&1 &...
import ipaddress import os import time import getpass import argparse from tetpyclient import RestClient import tetpyclient import json import requests.packages.urllib3 from argparse import ArgumentParser from collections import defaultdict from datetime import datetime import sys from tqdm import tqdm as progress impo...
#%% import numpy as np import os import pandas as pd from os import path from PIL import Image from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator import matplotlib.pyplot as plt import nltk import string from collections import Counter import re #%% # Import BOM # os.chdir('/Users/douglasvalentine/Library...
__author__ = 'himanshu' from models import Product """ class Product(models.Model): title = models.CharField(null=False, max_length=100) description = models.CharField(null=False) picture = models.ImageField(null=False) rating = models.IntegerField(null=False) price = models.DecimalField(null=False...
# -*- coding: utf-8 -*- from acid import db from acid.app import app class TestWithAppContext: def setup_method(self, method): self._ctx = app.app_context() self._ctx.push() def teardown_method(self, method): self._ctx.pop() class DatabaseTestCase: def setup_method(self, method)...
import os import platform import shutil class ClangToolchain: def __init__(self): # init. internal values self._clang_tidy_path = None self._run_clang_tidy_path = None self._clang_apply_replacements_path = None self._clang_format_path = None # trigger platform spe...
# Analisando e gerando Dicionários def notas(*n, sit=False): ''' ->Função para analisar notas e situações de vários alunos. :param n:uma ou mais notas dos alunos (aceita várias) :param sit: valor opcional, indica se deve ou não expor a situação do aluno :return: dicionário com várias informções do...
import random from bokeh.plotting import figure,show def got_sequences(throws): sequence = [] for _ in range(throws): option_got = random.choice([1, 2, 3, 4, 5, 6]) sequence.append(option_got) return sequence def graph(sim,prob,sum_to_reach,throws): plot = figure(title=print(f'Prob...
### # Copyright (c) 2005, Jeremiah Fincher # Copyright (c) 2009, James McCoy # 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 ...
import pandas as pd import tempfile, zipfile import os import numpy as np from collections import Counter class TestTableParser: def __init__(self, IsVerticalOrientation=False, index_rows=[], columns_types={}, mistake_fix=[], start_point=0): self.IsVerticalOrientation = IsVerticalOrientation self...
# # gemini_python # # primitives_resample.py # ------------------------------------------------------------------------------ import numpy as np from functools import reduce from copy import copy fr...
from tqdm import tqdm import pickle from os.path import dirname, join, abspath _BASIC_PATH = (join(dirname(dirname(dirname(abspath(__file__)))),"data")) def get_file_path(filename): return join(_BASIC_PATH, filename) def import_cleaned_training_set(): with open(get_file_path('processed\\lexicon_dataset_sm...
import string,random,time from p_locker import Credentials,UsersData def new_account(id,user_name,password): ''' Function to creating new account ''' new_user = Credentials(id,user_name,password) return new_user def create_user(user): ''' Function that saves the user's credentials ''' ...
import numpy as np import argparse import json from pylab import contour from PIL import ImageFilter, Image, ImageDraw import cv2 from skimage import measure import os import json import visvalingamwyatt as vw import glob import sys from pathlib import Path import pandas as pd from scipy.spatial import distance from sc...
""" blog_engine URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cl...
from http import HTTPStatus from io import BytesIO import pyqrcode from fastapi import Request from fastapi.params import Depends from fastapi.templating import Jinja2Templates from starlette.exceptions import HTTPException from starlette.responses import HTMLResponse, StreamingResponse from lnbits.core.models import...
import asyncio import pytest from aiojenkins.jenkins import Jenkins from tests import get_host, get_login, get_password @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() @pytest.fixture def jenkins(event_loop): async def _create_jenkins(): return Jen...
# -*- coding: utf-8 -*- import logging import re import time import traceback import requests from bs4 import BeautifulSoup from twilio.rest import Client logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # 通用HTTP请求头 headers = { 'Accept': 'text/html,application/xhtml+xml,application/x...
from dbparti import connection, transaction class BasePartition(object): """Base partition class for all backends. All backends should inherit from it.""" def __init__(self, column_value, column_type, **kwargs): self.cursor = connection.cursor() self.model = kwargs['object_name'] self....
import os, discord, random, time, sys, asyncio from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} ...
from django.contrib.auth.mixins import UserPassesTestMixin from django.shortcuts import get_object_or_404 from django.contrib.auth import get_user_model from portal.mixins import ProvinceAdminMixin class ProvinceAdminEditMixin(ProvinceAdminMixin): def test_func(self): # 404 if bad user ID profile...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
""" Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solu...
# 导入库 import numpy as np import argparse from matplotlib import pyplot as plt from scipy import stats from statistics import stdev import math import cv2 import os from xlwt import Workbook wb = Workbook() sheet1 = wb.add_sheet('Sheet 1') path = "test/image/" dir = "test/mask/" files = os.listdir(dir) #获得掩膜图片白色 files...
# Copyright 2022 PyQ Development Team # 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 wri...
# Generated by Django 2.2.1 on 2019-05-29 13:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('input', '0017_group_group_name'), ] operations = [ migrations.RemoveField( model_name='group', name='group_name', ),...
from jupyter_packaging.setupbase import get_data_files def test_empty_relative_path(tmpdir): tmpdir.mkdir("sub1").join("a.json").write("") tmpdir.mkdir("sub2").join("b.json").write("") spec = [("my/target", "", "**/*.json")] res = get_data_files(spec, top=str(tmpdir)) assert sorted(res) == [ ...
import importlib import numpy as np from pytracking.features.net_wrappers import NetWithBackbone from .base import Tracker class PytrackingTracker(Tracker): """Wrapper around PyTracking Trackers. This re-implements some code from pytracking.evaluation.Tracker, removing parts of the code from that clas...
import numpy as np import json import matplotlib.pyplot as plt with open("party.json", "r") as read_file: rawpart = json.load(read_file) part=[] for item in rawpart: part.append(item["name"]) with open("opinion.json", "r") as read_file: rawdata = json.load(read_file) data = np.zeros((32,38)) #party, statement fo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 腾讯地图示意图 from __future__ import print_function import random import folium from folium.features import DivIcon from folium.plugins import MarkerCluster, RotatedMarker, PolyLineTextPath, DirectedLine def tencent_marker(out_dir="../../out"): """ 腾讯地图,打点 :param...
""" Null model for predicting pairwise distances based on minimum path length between pairs of atoms. """ import itertools import json from logging import Logger import matplotlib.pyplot as plt import numpy as np import os import pickle # noinspection PyUnresolvedReferences from rdkit import Chem # noinspec...
import os import sys import subprocess import psutil from ..main import main, monitor, all_children TEST_CODE = """ import subprocess p = subprocess.Popen('sleep 5'.split()) p.wait() """ def test_all_children(tmpdir): filename = tmpdir.join('test.py').strpath with open(filename, 'w') as f: f.write...
""" Here lie methods for ouputing as images--aka Graphics. R.I.P """ import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from .generate import error def draw_canvas(canvas, max_height): """ Draw the given table """ fig, ax = plt.subplots(1, 1) ax.pcolor(canvas,...
from unittest import TestCase from supergsl.core.tests.fixtures import SuperGSLCoreFixtures from supergsl.core.constants import ( SO_PROMOTER, PART_SLICE_POSTFIX_START, PART_SLICE_POSTFIX_END ) from supergsl.core.ast import SlicePosition as AstSlicePosition from supergsl.core.types.part import convert_slice...
from argparse import ArgumentParser from os import listdir from os.path import isfile, isdir from zmigrate.config import load as load_config from zmigrate.range import Range from zmigrate.dir import Dir from zmigrate.drivers import SUPPORTED_DRIVERS def str_to_bool(v): if isinstance(v, bool): return v i...
import os import ast as ast39 import time from typed_ast import ast27 from collections import deque from urllib import request from compare_string_version import compareVersion def ast_parse(code): # ast related: refer to Python doc >> ast try: body = ast39.parse(code).body this_ast = ast39 ...
import pytest from covidmx import CovidMX def test_makes_plot(): try: dge_plot = CovidMX().get_plot() for st in dge_plot.available_status: file_name = '{}.png'.format(st) mx_map = dge_plot.plot_map(status=st, save_file_name=file_name) mx_map_with_muns = dge_plot...
import glob import hashlib import logging import os import random import sys from itertools import product import numpy as np import pandas as pd import yaml from attrdict import AttrDict from deepsense import neptune from tqdm import tqdm def read_yaml(filepath): with open(filepath) as f: config = yaml....
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.6.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Weather Data from Global Hi...
def getCoinCount(amount, coins): dp = [float('inf')] * (amount+1) dp[0] = 0 print dp for i in xrange(amount): for c in coins: if i + c > amount: continue dp[i+c] = min(dp[i+c], dp[i]+1) return dp def change(n, coins_available, coins_so_far): if ...
from urllib.parse import urljoin, quote_plus def multi_urljoin(*parts): return urljoin(parts[0], "/".join(quote_plus(part.strip("/"), safe="/") for part in parts[1:]))
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib import admin import logging import re try: import django.contrib.staticfiles view = 'django.contrib.staticfiles.views.serve' except ImportError: view = 'django.views.static.serve' # for Django 1.2 lo...
###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
from setuptools import setup from Cython.Build import cythonize setup(ext_modules=cythonize('NURBS_C.pyx'))
""" Author: Salva Rühling Cachay """ import os import time import numpy as np import torch import torch.nn.functional as F from eval_gcn import evaluate_preds from utilities.data_wrangling import load_cnn_data, to_dataloaders from utilities.utils import get_euclidean_adj def train_epoch(dataloader, model, criterio...
import itertools def n_queens(n): """Return a solution to the n-queens problem for an nxn board. This uses E. Pauls' explicit solution, which solves n > 3. A solution is possible for all n > 3 and n = 1. Pauls' solution gives back 1-based indices, and we want 0-based, so all points have an extra -...
from pandas_bigquery.exceptions import * from pandas_bigquery.gbqconnector import GbqConnector from pandas_bigquery.datasets import Datasets from time import sleep class Tables(GbqConnector): def __init__(self, project_id, reauth=False, verbose=False, private_key=None): try: from googleapiclie...
from tools import filter, monitor from tools.common import highlight if __name__ == "__main__": while True: command = input(highlight("""\n1 - 手动检索新闻 / 文本文件 / xlsx 表格 / 图片 2 - 新闻实时跟踪 q - 退出: 请输入指令: """, 31)) if command == "1": filter.main() elif command == "2": m...
ctx.addClock("clk_i", 12)
import pandas as pd df = pd.read_csv('token_freq.csv') print(df)
{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "\n", "# lINKED list in python\n", "# @AUTHOR - AMRESH TRIPA...
try: from PIL import Image except ImportError: import Image import os import pytesseract from beastx.Configs import Config from . import * @beast.on(beastx_cmd(pattern="read$")) async def _(event): global images if event.fwd_from: return await event.edit("`Reading, Pleas...
import os, json import geopandas as gpd import pandas as pd import multiprocessing as mp from multiprocessing.shared_memory import SharedMemory import numpy as np import pyproj from shapely import geometry, ops, wkt from functools import partial def get_utm_zone(lat,lon): """A function to grab the UTM zone numbe...
# 2.6.9 asynchat.py # 2.6 added: # return_stmt ::= ret_expr RETURN_END_IF come_from_pop def initiate_send(self): while self: if self: x = 'a' else: del self.producer_fifo[0] return # 2.6.9 contextlib.py # Bug was in return exc, so added: # return_stmt ::= ret_expr RE...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack, 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...
""" This is a command line interface for SoundcloudDownloader. """ import argparse from SoundcloudDownloader import SCDL def main(): parser = argparse.ArgumentParser( description="Download songs from Soundcloud." ) parser.add_argument( '-d', '--directory', help='Directory to download to.'...
#!/usr/bin/env python from re import sub from sys import argv,exit from os import path,getenv,system from array import array from glob import glob import argparse parser = argparse.ArgumentParser(description='interpolate') parser.add_argument('--mass_interp',type=str) parser.add_argument('--mass_reco',type=str,default...
""" @name: Modules/Core/Drivers/_test/test_Serial.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2015-2019 by D. Brian Kimmel @license: MIT License @note: Created on Jul 30, 2015 @Summary: """ __updated__ = '2019-10-08' # Import system type stuff import xml.etree.Eleme...
import mysql.connector import smtplib from collections import defaultdict from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mydb = mysql.connector.connect( host="localhost", user="admin", passwd="admin1234", database="wdrDb" ) mycursor = mydb.cursor() mycursor.execut...
from __future__ import division from openconcept.components.turboshaft import SimpleTurboshaft from openconcept.components.propeller import SimplePropeller from openconcept.utilities.dvlabel import DVLabel from openconcept.utilities.math import AddSubtractComp, ElementMultiplyDivideComp from openmdao.api import Group, ...
from fhir_helpers.resources.lpr import LPR from fhir_helpers.utils import ensure_non_null_date from .helpers import get_example_bundle, get_example_bundle_proto def test_practicioner_find() -> None: lpr_dict = LPR(get_example_bundle()) lpr_proto = LPR(get_example_bundle_proto()) assert len(lpr_dict.prac...
import re from django import template from django.contrib import admin from django.contrib.admin import AdminSite from django.conf import settings from django.http import HttpRequest from django.urls import reverse, resolve from django.utils.safestring import mark_safe from django.forms.models import ModelMultipleChoic...
import numpy as np import tensorflow as tf import gym import time import sys import copy from algos.tf1.offPolicy.baseOffPolicy import OffPolicy from algos.tf1.ddpg_sp import core from algos.tf1.ddpg_sp.core import get_vars # 在tf中,MPI只需要将优化器替换掉,替换成能求各个进程平均梯度的优化器。 from spinup_utils.mpi_tf import MpiAdamOptimizer import...
""" Takes BED files of genomic features (such as promoters) and generates a 4-column WIG-style file for the Hi-C viewer, with 1 where features are and 0 for other positions. Wrote to parse files from promoter database https://epd.epfl.ch/ """ from optparse import OptionParser import sys import re import numpy as ...
my_dict={ 'name':'Tom', 'id':123 } print(my_dict) print(my_dict.keys()) print(my_dict.values()) my_dict.pop('id') print(my_dict) my_tweet={ 'tweet_id':1138, 'coordinates':(-75,40), 'visited_countires':['GR','HK','MY'] } print(my_tweet) print(len(my_tweet['visited_countires'])) my_tweet['v...
""" Exercise 23 - Multilevel Indexing Question: Access the third value of key b from the dictionary. from pprint import pprint d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31))) Expected output: 13 Hint: You need square brackets after square brackets here. """ fr...
# Lesson 5 # This declares an empty list inputs = [] # This reads like plain old English. While the length of our input is less than 5... while len(inputs) < 5: x = input('Next: ') inputs += [x] # We must put x in a list to append it # inputs.append(x) # We can also append this way print(inputs) iter...
# -*- coding: utf-8 -*- # Copyright: (c) 2012, Brian Scholer (@briantist) # 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 class ModuleDocFragment(object): DOCUMENTATION = r''' ...
# Copyright 2021 The KNIX 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 agree...
import numpy as np import argparse import pickle from cvxOpt import Log_Log, SVM_Log from cvxpyMdl import Log_SVM,SVM_SVM import sys from sklearn import metrics from scipy.io import savemat from compute_statistics import get_acc_precison_recall def train_predict_score(loss, abs_train_feat, abs_train_label, cmp_train_...