text stringlengths 1 927k |
|---|
#!/usr/bin/env python3
# Copyright (c) 2016-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the bumpfee RPC.
Verifies that the bumpfee RPC creates replacement transactions successfully when... |
# -*- coding: utf-8 -*-
__author__ = """Christoph Rist"""
__email__ = "c.rist@posteo.de"
import tensorflow as tf
def assert_normalized_quaternion(quaternion: tf.Tensor):
with tf.control_dependencies(
[
tf.debugging.assert_near(
tf.ones_like(quaternion[..., 0]),
... |
import logging
# Getting the name of the module for the log system
logger = logging.getLogger(__name__)
# Definition of reggex patterns
HEADER_OPLS2005 = "* LIGAND DATABASE FILE (OPLS2005)\n*\n"
PATTERN_OPLS2005_RESX_HEADER = "{:5} {:6d} {:6d} {:7d} {:7d} {:8d} \n"
PATTERN_OPLS2005_RESX_LINE = "{:5d} {:5d} {:1} {:4... |
import platform
import hashlib
import requests
import stat
from contextlib import contextmanager
import re
import docker
try:
import arrow
except ImportError: pass
from pathlib import Path
import io
import traceback
import json
import pipes
import tempfile
from datetime import datetime
try:
from retrying import... |
n=int(input("enter a number"))
count=0
sum=0
while(n>0):
count=count+1
d=n%10
sum=sum+d
n=n//10
print("sum of number of digit of entered number is",sum)
print("the number of digit in the number are",count) |
from machine import Pin, SoftI2C
from lib.config import *
from lib.oled.ssd1306 import SSD1306_I2C
import urequests
import json
# Oled Display
i2c = SoftI2C(sda=Pin(DEFAULT_IOTKIT_I2C_SDA), scl=Pin(DEFAULT_IOTKIT_I2C_SCL))
display = SSD1306_I2C(128, 64, i2c)
###
# Verbindung zum Cloud Dienst
#
req = urequests.request... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
import operator
from functools import reduce
import sqlalchemy.types as sqltypes
from six import iteritems
from six.moves.urllib_parse import unquote_plus
from snowflake.connector import errors as ... |
from pylab import *
import tables
import pylab
from matplotlib import rcParams
import matplotlib.pyplot as plt
# customization for figure
#rcParams['lines.linewidth'] = 2
rcParams['font.size'] = 18
#rcParams['xtick.major.size'] = 8 # default is 4
#rcParams['xtick.major.width'] ... |
##############################################################################
#
# Copyright (c) 2003-2020 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development unti... |
"""
Script for serving a trained chatbot model over http
"""
import datetime
import click
from os import path
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from flask_restful import Resource, Api
import general_utils
import chat_command_handler
from chat_settings import ChatSettings... |
import json
import numpy as np
import pytest
import tensorflow as tf
from google.protobuf import json_format
from seldon_e2e_utils import post_comment_in_pr, run_benchmark_and_capture_results
@pytest.mark.benchmark
@pytest.mark.usefixtures("argo_worfklows")
def test_service_orchestrator():
sort_by = ["apiType"... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
# encoding:utf-8
'''Remove audio from video with FFmpeg (4.1.x).
从视频中删除音频
Author: He Zhang @ University of Exeter
Date: 16th April 2019 (Update: 18th April 2019)
Contact: hz298@exeter.ac.uk zhangheupc@126.com
Copyright (c) 2019 He Zhang
'''
# Python 3.7
import os
import subprocess
# Set the path of input and outpu... |
# ------------------------------------------------------------------------------
# Path setup
# Variables ending in _PATH are used as URL paths; those ending with _FSPATH
# are filesystem paths.
# For a single board setup (wakaba style), set SITE_PATH to / and point
# MATSUBA_PATH to /boardname/matsuba.py
# The base... |
class MessageReceiver:
def receive_msg(self, message):
raise NotImplementedError |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 20:12:44 2019
@author: ben
"""
def matlab_to_year(t):
# approximate conversion of matlab date to year. Uses the matlab conversion
# datestr('jan 1 2000') -> 730486
return (t-730486.)/365.25+2000. |
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib... |
# -*- coding: utf-8 -*-
import rhyme_words_tc as rhyme_words
def PingShuiYunInit(sheet, mainIndex, secondIndex, Chars):
i = 0
while i < len(Chars):
oneChar = Chars[i]
if oneChar in "[]":
i += 1
continue
if i != len(Chars) - 1:
if Chars[i + 1] == '['... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 17:32:08 2020
@author: apramanik
"""
import numpy as np
import SimpleITK as sitk
import torch
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
#%% Functions
def normalize_img(img):
img = img.copy().astyp... |
import os
import pytest
import opencell.database.utils as db_utils
def test_format_plate_design_id():
valid_plate_ids = [123, 'plate123', 'Plate 123', '0123']
for plate_id in valid_plate_ids:
assert db_utils.format_plate_design_id(plate_id) == 'P0123'
# plate number can be zero
valid_plate_i... |
# @Author: Manuel Rodriguez <valle>
# @Date: 10-May-2017
# @Email: valle.mrv@gmail.com
# @Last modified by: valle
# @Last modified time: 11-Jul-2017
# @License: Apache license vesion 2.0
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.storage.jsonstore import Jso... |
from src.InvertedPendulum import *
from src.Simulator import *
from src.controllers.LQRController import *
# This script shows the behavior of the pendulum controlled by an LQR controller
if __name__ == "__main__":
# Import model
model = InvertedPendulum()
# Set initial state [m, m/s, rad, rad/s... |
from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
key = b'1234567891234567'
value = b'1234567'
value1 = b'1234567812345678'
iv = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
crypt_sm4 = CryptSM4()
crypt_sm4.set_key(key, SM4_ENCRYPT)
encrypt_value = crypt_sm4.crypt_ecb(value)
crypt_sm4.se... |
from logging import getLogger
import slack
logger = getLogger(__name__)
class ChannelListNotLoadedError(RuntimeError):
pass
class ChannelNotFoundError(RuntimeError):
pass
class FileNotUploadedError(RuntimeError):
pass
class SlackAPI(object):
def __init__(self, token, channel: str, to_user: st... |
#!/usr/bin/python2
import pandas as pd;
import SETTINGS as sts;
from fitting_models import *
import analysis
def train_sex_age_model(info, train_true):
##train sex_age model
print(" ------ train sex age model :");
sa_model = SexAgeModel();
sa_model.fit(info,train_true);
sa_predict = sa_model.predic... |
def display_power(power: dict) -> str:
name = power['name']
invocation_unit = power['invocation']['card_name']
invocation_instances = power['invocation']['num_instances']
cost = power['cost']
return f'{name} (Invocation: {invocation_instances} {invocation_unit}) - Cost: {cost}' |
import os
from pascal_voc_writer import Writer as PascalWriter
def test_1(results_dir):
pascal_writer = PascalWriter('test-image.png', 100, 100)
pascal_writer.addObject(name='triangle', xy_coords=[5, 5, 95, 5, 50, 95])
pascal_writer.save(os.path.join(results_dir,
'test-... |
from app.bot import Bot
if __name__ == '__main__':
Bot().run() |
# -*- coding: utf-8 -*-
"""Module with data plugins that represent files of completed calculations jobs that have been stashed."""
from .base import RemoteStashData
from .folder import RemoteStashFolderData
__all__ = ('RemoteStashData', 'RemoteStashFolderData') |
# this file was created by Chris Cozort
# Sources: goo.gl/2KMivS
# now available in github
'''
Curious, Creative, Tenacious(requires hopefulness)
Game ideas:
Walls closing in on player
'''
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game:
def __init_... |
import torch
import numpy as np
import os
from torch.utils.data import TensorDataset, DataLoader
from .utils import collate_sequences
NORMALIZER = { # (mu, std) per class computed on the concatenation of both features (discarding the binary feature)
'hot dog': (1.3554527691145501, 55.15028414343622),
'palm tr... |
# 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 agreed to in ... |
#!usr/bin/env python
##########################################################
# #
# commandsshbotnet.py #
# author: @shipcod3 #
# inspired by the mass ssh botnet in " Violent Python " #
# ... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import time
import datetime
import os
import sys
import h5py
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
import evidential_deep_learning as edl
from .util import normalize, gallery
class BBBP:
def __in... |
xml = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:meld="http://www.plope.com/software/meld3"
xmlns:bar="http://foo/bar">
<head>
<meta content="text/html; charset=ISO-8859-1... |
#!/usr/bin/env python
"""Tests for Queue."""
from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib.aff4_objects import queue as aff4_queue
class TestQueue(aff4_queue.Queue):
rdf_type = rdfvalue.RDFInteger
class Que... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 10
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_9_0_0
from ... |
import re
import numpy.ma as ma
from osgeo import gdal, osr
from pextant.lib.geoshapely import *
from pextant.lib.geoutils import filled_grid_circle
from pextant.mesh.abstractmesh import GeoMesh, EnvironmentalModel, \
SearchKernel, coordinate_transform, Dataset, NpDataset
from pextant.mesh.abstractcomponents impo... |
import cv2
import ast
import torch
import numpy as np
import random
from torch.utils.data import DataLoader, Dataset
cv2.setNumThreads(1)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class VimeoDataset(Dataset):
def __init__(self, dataset_name, batch_size=32):
self.batch_size = bat... |
""" Unit tests for positional_list.PositionalList """
from dloud_ads import positional_list
def test_dummy():
"""Test definition"""
the_list = positional_list.PositionalList()
pos8 = the_list.add_last(8)
assert pos8.element() == 8
assert the_list.first().element() == pos8.element()
pos5 = the... |
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
from misconceptions.rUtils import functions
def process_file(file_path):
r_functions = functions.get_r_functions(file_path)
n_valid = 0
print("Processing %d functions from '%s' ... " % (len(r_funct... |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a > b:
print('a > b')
if a > b and a > b:
print('a > b again')
if a > b and a < d:
print('b < a < d')
if not a > b:
print('not a > b')
if b < a < d:
print('b < a < d again')
if a > b == True:
print('a > b and True')
if... |
import sys
sys.path.append('../')
sys.path.append('../support/')
from scipy.ndimage.measurements import label
from scipy.ndimage import interpolation
from time import time
from glob import glob
import timeit
from os.path import join, basename, isfile
from tqdm import tqdm
from paths import *
from ct_reader import *
imp... |
"""SCons.Tool.suncc
Tool-specific initialization for Sun Solaris (Forte) CC and cc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
Intuition app entry point
--------------------------
:copyright (c) 2014 Xavier Bruhiere
:license: Apache 2.0, see LICENSE for more details.
'''
import sys
from intuition.cli import main
if __name__ == '__main__':
sys.exit(main()) |
from devito.ir.iet.nodes import * # noqa
from devito.ir.iet.visitors import * # noqa
from devito.ir.iet.utils import * # noqa
from devito.ir.iet.efunc import * # noqa
from devito.ir.iet.algorithms import * # noqa |
{
###################################
# User data should be added below #
###################################
# e.g. "aidPage" is default function in W3 and do not need to specify here #
#"aidPage": {
# W3Const.w3ElementType: W3Const.w3TypeApi,
# W3Const.w3ApiName: "page",
# W3... |
import re
import ast
import logging
import operator as op
def _stepdown_rest(entry) -> list:
'''move the elements one level down into the existing JSON hierarchy.
if `entry` has the structure {'vrfs': {'routes'...} on invocation,
it'll be {'routes'...} on exit. It makes no sense to move down them
hie... |
from os.path import expanduser
import dask.dataframe as dd
import os
import pandas as pd
from pandas import DataFrame
# ------------------------------- KEYWORD -------------------------------------------------------------------------
home = expanduser("~")
d1 = os.path.expanduser("~/.cache/dein/repos/github.com/ta... |
# Copyright 2018 The TensorFlow 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 applica... |
import json
import os
from importlib import import_module
from inspect import getfullargspec, FullArgSpec
from cloudpickle import dump, load
import itertools
import sklearn
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
fr... |
import json
import os
import sys
import time
from typing import List, Optional, Dict
import progressbar
from dateutil.parser import parse
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "..")))
import pypi_org.data.db_session as db_session
from pypi_org.data.languages import Pro... |
# noqa D100
import sys
import mock
def _setup():
global bh1745
from tools import SMBusFakeDeviceNoTimeout
smbus = mock.Mock()
smbus.SMBus = SMBusFakeDeviceNoTimeout
sys.modules['smbus'] = smbus
from bh1745 import BH1745
bh1745 = BH1745()
def test_set_adc_gain_x():
"""Test setting adc... |
#!/usr/bin/env python
# numpy package
import numpy as np
# torch package
import torch
import torchvision
from torch.nn.functional import cross_entropy, softmax, log_softmax
# basic package
import os
import sys
sys.path.append('.')
import argparse
from tqdm import tqdm
from datetime import datetime
# custom package
... |
"""project 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')
Class-based... |
class UnauthorizedException(Exception):
def __init__(self):
super(UnauthorizedException, self).__init__('User not authenticated.')
class ForbiddenException(Exception):
def __init__(self):
super(ForbiddenException, self).__init__('User not authorized.')
class ConflictException(Exception):
... |
import json
import pandas
import urllib3
from classmerge import match
from dataclean import cleanall
df = pandas.read_csv("dataset/valid-phase1.csv")
http = urllib3.PoolManager()
correct = 0
for index, row in df.iterrows():
label = row[0]
title = row[1].replace(".doc","").replace(".docx","")
content = cle... |
from matrices import Matrix
from tuples import Point
from canvas import Canvas
from colours import Colour
from math import pi
def run():
# our clock face will be drawn in the x-y plane, so z-components will always be 0
WIDTH = 500
HEIGHT = 500
c = Canvas(WIDTH, HEIGHT)
for i in range(12):
... |
# -*- coding: utf-8 -*-
# Use this file to easily define all of your cron jobs.
#
# It's helpful to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
#
# Learn more: http://github.com/fengsp/plan
from plan import Plan
cron = Plan("scripts", path='/web/yourproject/scripts',
... |
# Generated by Django 2.1.3 on 2018-12-03 15:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Host',
fields=[
('id', models.AutoField(aut... |
# File: rt_connector.py
# Copyright (c) 2021 Splunk Inc.
#
# SPLUNK CONFIDENTIAL - Use or disclosure of this material in whole or in part
# without a valid written license from Splunk Inc. is PROHIBITED.
# Phantom imports
import phantom.app as phantom
from phantom.base_connector import BaseConnector
from phantom.actio... |
"""Auto-generated file, do not edit by hand. WS metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_WS = PhoneMetadata(id='WS', country_code=685, international_prefix='0',
general_desc=PhoneNumberDesc(national_number_pattern='[2-8]\\d{4,6}', possible_number_pattern='... |
# -*- coding: utf-8 -*-
"""
@authors: Suhas Sharma and Rahul P
"""
"""
Error codes can be found at the end of this file
"""
import ipaddress as ip
import urllib.parse as urlparse
import ssl
import socket
import requests
from bs4 import BeautifulSoup as bs
from ast import literal_eval
import urllib
import re
from dat... |
#
# Symbol Table
#
from __future__ import absolute_import
import re
import copy
import operator
try:
import __builtin__ as builtins
except ImportError: # Py3
import builtins
from .Errors import warning, error, InternalError
from .StringEncoding import EncodedString
from . import Options, Naming
from . im... |
from decimal import Decimal
_ = lambda x:x
#from i18n import _
from electrum import WalletStorage, Wallet
from electrum.util import format_satoshis, set_verbosity
from electrum.bitcoin import is_valid, COIN, TYPE_ADDRESS
from electrum.network import filter_protocol
import sys, getpass, datetime
# minimal fdisk like gu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Imitando el buscaminas de windows, esto es un tributo al juego ese
# en el que perdimos tanto tiempo, pero hecho en python3/tkinter
# La idea de hacer esto surgió en casa de Julio, pc nueva, sin juegos,
# un tonto propuso "hagamos el buscaminas en python", y bueno no se
# ... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
import requests
import sys, os
import json
def main():
if (len(sys.argv) < 3):
print('you need to give atleast url and HTTP-reguest type!')
return
url = sys.argv[1]
type = sys.argv[2]
if (type == 'POST' or type == 'PUT'):
if (len(sys.argv) < 4):
print('you also nee... |
""" Description here
Author: Leonard Berrada
Date: 5 Nov 2015
"""
import sys
sys.path.append("../")
import matplotlib.pyplot as plt
from Regression import AutoRegressive, AutoCorrelation, GaussianProcess, KalmanFilter
from process_data import data_from_file
file_name = "co2.mat"
data_dict = data_from_file(file_... |
from __future__ import generators
import os, math, random
import gamesrv
from bubbob import images
from bubbob.images import ActiveSprite
from bubbob.boards import CELL, HALFCELL, bget
from bubbob.mnstrmap import GreenAndBlue, Ghost
from bubbob.bonuses import Bonus
from bubbob.bubbles import Bubble
LocalDir = os.path.... |
# Copyright (C) 2018 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 writ... |
# Modifications Copyright 2016-2017 Reddit, Inc.
#
# Copyright 2013-2016 DataStax, 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
#
# Unle... |
import requests
import json
from datetime import datetime
import os
REQUEST_HEADERS = {
'authority': 'www.bloomberg.com',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.... |
#!/usr/bin/env python
import sys
import os
import subprocess
import time
from os.path import abspath as _abspath, join as _join
from mpi4py import MPI
import random
#---------------------------------------------
# Main start here
#---------------------------------------------
# Obtain MPI rank
def main():
start_g... |
import gym
import time
import pickle
import argparse
import numpy as np
import tensorflow as tf
from typing import Callable, Union, Tuple, List
from models.models import actor_fc_discrete_network, actor_critic_fc_discrete_network
from algorithms.imitation.utils import plot_training_results
from util.replay_buffer impor... |
# Calculate the amount of money for certain number of bananas
bananaPrice = 1
numberOfBanana = 3
cost = bananaPrice * replaceMe
print(cost) |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 12:08:46 2019
@author: antonio.furnari
"""
from __future__ import print_function
if __name__ == '__main__':
n = int(raw_input())
for i in range(1, n+1):
print (i, end='') |
from django.contrib import admin
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import gettext_lazy as _
from .models import Author, Category, Post, PostCategory, Comment
# class FlatPageAdmin(FlatPageAdmin):
# fieldsets ... |
#-
# Copyright (c) 2011 Robert N. M. Watson
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# License... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd #for pandas see http://keisanbutsuriya.hateblo.jp/entry/201\
import argparse
import numpy as np
import math
import subprocess
import glob
import os
from matplotlib import pylab as plt
from numpy.lib.stride_tricks import as_strided
S=['fhs', 'fms', 'mkk'... |
from __future__ import print_function
from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)
from xvfbwrapper import Xvfb
@magics_class
class XvfbMagics(Magics):
def __init__(self, shell, **xvfb_kwargs):
"""
Initialize the Xv... |
import logging
import sys
import yfinance
import pandas as pd
import yfinance as yf
import os
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Any, Dict, List
from finrl.config import TimeRange, setup_utils_configuration
from finrl.data.converter import convert_ohlcv_fo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
import numpy as np
# Generate some n number of colours, hopefully maximally different
# source: http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors
import colorsys
def get_colors(num_colors):
colors=[]
for i in np.arange(0., 360., 360. / num_colors):
hue = i/360... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
import torch.nn.functional as F
from fairseq_mod import metrics, utils
from fairseq_mod.criteri... |
import sys
import pywikibot
from gorgonwikibot.content import (Ability, Ai, get_all_content,
get_content_by_iname)
from gorgonwikibot.entrypoint import entrypoint
def get_abilities(validator=lambda _: True, include=[]):
return {
a.iname: {
"Description": a.d... |
# Third-Party
import pytest
from rest_framework.test import APIClient
# from rest_framework.test import RequestsClient
# Django
from django.test.client import Client
# First-Party
from .factories import AwardFactory
from .factories import ChartFactory
from .factories import ConventionFactory
from .factories import G... |
import json
import sys
import os
from tqdm import tqdm
from mdf_refinery.parsers.tab_parser import parse_tab
from mdf_refinery.validator import Validator
# VERSION 0.3.0
# This is the gdb8-15 dataset: Electronic Spectra from TDDFT and Machine Learning in Chemical Space
"""If feedstock path gets changed in an mdf vers... |
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class RootObjectUD(DistributedObjectUD):
def __init__(self, air):
DistributedObjectUD.__init__(self, air) |
from setuptools import setup
setup(name='simpholib',
version='1.0b1',
description='Simple Photo Library',
long_description='Tool for ordering unsorted photos and arrange them in a directories by dates.',
url='https://github.com/dstdnk/simple-photo-library',
download_url='https://github.co... |
from conans import ConanFile, CMake
class AwsConan(ConanFile):
name = "aws-sdk-cpp"
version = "1.3.21"
license = "Apache License 2.0"
description = "AWS SDK for C++"
url = "https://github.com/aws/aws-sdk-cpp"
settings = "arch", "build_type", "compiler", "os"
generators = "cmake"
def p... |
#!/usr/bin/env python2.7
import os
import sys
import inspect
import time
import argparse
script_folder = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
parent_folder = os.path.split(script_folder)[0]
sys.path.append(parent_folder)
import exp_config
# first we initializ... |
# Generated by Django 2.2.19 on 2021-11-26 12:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_post_group'),
]
operations = [
migrations.AlterModelOptions(
name='post',
options={'ordering': ['-pub_date']}... |
import gym
import torch
import multiprocessing as mp
import numpy as np
from maml_rl.envs.subproc_vec_env import SubprocVecEnv
from maml_rl.episode import BatchEpisodes
def make_env(env_name):
def _make_env():
return gym.make(env_name)
return _make_env
class BatchSampler(object):
def __init__(sel... |
import numpy
import theano
from theano.tensor.var import _tensor_py_operators
from theano import Type, Variable, Constant, tensor, config, scalar
from theano.compile import SharedVariable
# Make sure this is importable even if pygpu is absent
# (it will not work though)
try:
import pygpu
from pygpu import gpu... |
"""
Utilities for loading inference data into the model
"""
# TODO refactor so xml_loader and inference_loader import from a utilities directory
from ingestion.ingest_images import load_image, load_proposal, get_example_for_uuid
from torch.utils.data import Dataset
import torch
import os
from os.path import splitext
fr... |
# coding=utf-8
# Copyright 2019 The Google Research 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 applicab... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import operator
from functools import partial, reduce
import torch
from torch.distributions.utils import _sum_rightmost
from pyro.nn import ConditionalDenseNN, DenseNN
from .. import constraints
from ..conditional import Conditi... |
from trainer import Trainer
from infenrence import BeamSearcher
import config
def main():
if config.train:
trainer = Trainer()
trainer.train()
if config.test:
beamsearcher = BeamSearcher(config.model_path, config.output_dir)
beamsearcher.decode()
if __name__ == "__main__":
... |
from data.config import cfg, process_funcs_dict
from data.coco import CocoDataset
from data.loader import build_dataloader
#from modules.solov1 import SOLOV1 as solo
# from modules.solov2 import SOLOV2 as solo
from modules.solov1d import SOLOV1 as solo
import time
import torch
import numpy as np
# 梯度均衡
def clip_grads(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.