text stringlengths 2 999k |
|---|
from collections import defaultdict, Counter
import itertools
from operator import __mul__
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from geosolver.grounding.ground_formula import _ground_variable
from geos... |
description = 'Devices for the normal SANS sample holder'
pvprefix = 'SQ:SANS:mcu1:'
excludes = ['emagnet_sample']
devices = dict(
z = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'Sample Table Height',
motorpv = pvprefix + 'z',
errormsgpv =... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ewallet.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are ... |
#!/usr/bin/env python
# COnvert all notebooks to .rst format and save them
# in the ../doc folder
from __future__ import print_function
import glob
import subprocess
import shutil
import os
notebooks = glob.glob("*.ipynb")
for nb in notebooks:
root = nb.split(".")[0]
cmd_line = 'ipython nbconvert ... |
import asyncio
import json
import logging
import requests
from typing import Any, Callable, List, TextIO
import jwt
import socketio
_logger = logging.getLogger('cncjs-py-pendant')
def debug_log_handler_factory(prefix: str) -> Callable[..., None]:
def debug_log_handler(*args) -> None:
_logger.debug(f'{p... |
import numpy as np
import pyrealsense2 as rs
import pcl
from swagscanner.scanner.camera import Camera
class SR305(Camera):
'''Camera object
'''
def __init__(self):
# Configure depth stream
self.pipeline = rs.pipeline()
self.config = rs.config()
self.config.enable_stream(
... |
import patch
import dash_devices
from dash_devices.dependencies import Input, Output, State
from dash_html_components import P
import dash_core_components as dcc
import plotly.express as px
import plotly.graph_objects as go
from threading import Timer
from websocket import create_connection
from datetime import date... |
from fastapi import APIRouter
from app.api.v1.endpoints.auth import auth
from app.api.v1.endpoints.users import users
API_VERSION = "v1"
api_router = APIRouter()
api_router.include_router(auth.router, prefix=f"/api/{API_VERSION}/auth", tags=["auth"])
api_router.include_router(users.router, prefix=f"/api/{API_VERSION... |
#!/usr/bin/env python
'''
Copyright (C) 2013 Carl Sorensen carl.d.sorensen@gmail.com
Derived from grid_cartesian.py copyright (C) 2007 John Beard john.j.beard@gmail.com
##This extension allows you to draw a two-point perspective grid in Inkscape.
##There is a wide range of options including subdivision, subsubdivion... |
#!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import unittest
from PIL import Image
import chrome_utils
from ..common import mock_cloud_bucket
class ChromeUtilsTest... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from . import extension_base
class Extension(extension_base.Extension):
def __call__(self, build_ext):
build_ext.distribution.has_c_libraries = self.has_c_libraries
extension_base.Extension.__call__(self, build_ext)
... |
class base:
def __init__(self):
self.url = "http://patft.uspto.gov/netacgi/nph-Parser"
self.url2 = "http://patft.uspto.gov"
self.params = {
'Sect1': 'PTO2',
'Sect2': 'HITOFF',
'u': "/netahtml/PTO/search-adv.htm",
'r': '0',
'f': 'S... |
import logging
import argparse
import os
import random
import sys
import numpy as np
import torch
import transformers
import pickle
from transformers import AutoTokenizer
from sklearn.model_selection import train_test_split
import json
def main(args):
print("loading tokenizer")
texts, labels = [], []
print(... |
# encoding: utf-8
"""
@author: sherlock
@contact: sherlockliao01@gmail.com
"""
import logging
from ignite.engine import Events
from ignite.engine import create_supervised_evaluator
from ignite.metrics import Accuracy
def inference(
cfg,
model,
val_loader
):
device = cfg.MODEL.device
... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
import os
from spack import *
class Tioga(CMakePackage, CudaPackage):
"""Topology Independent Overset Grid... |
from allauth.account.models import EmailAddress
from allauth.socialaccount.app_settings import QUERY_EMAIL
from allauth.socialaccount.providers.base import AuthAction, ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class Scope(object):
EMAIL = 'email'
PROFILE = 'pro... |
import numpy as np
import unittest
import os
import shutil
folder = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
class TestFixNodeVelocitywrtA(unittest.TestCase):
def setUp(self):
import sharpy.utils.generate_cases as gc
deg2rad = np.pi/180.
nodes_per_elem = 3
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=19
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Ci... |
'''
trackeddy is written in Python. It tracks each oceanic eddy.
See README.md for an overview on instructions and the iPython
notebook manual.ipynb for instructions on use. A user manual for
trackeddy is available online.
Modules available in trackeddy include:
* datastruct.py
* init.py
* geometryfunc.py (Developed ... |
from .errors import RedisValueError, RedisTypeError
from .datatypes import RedisSortable
from collections import Sequence
class Sequence(RedisSortable, Sequence):
"""
Sequence datatype that implements all functions of ``Redis list``
datatypes.
Compared to ``List``, a ``Sequence`` doesn't try to meme ... |
"""
File name : early_stopping.py
Description : Early stopping callback
Date created : 07.03.2021
Author: Ihar Khakholka
"""
import numpy as np
import logging
from training.callbacks.base import Callback
class EarlyStopping(Callback):
r"""
Monitor a validation metric and stop training when it stop... |
#
#
# 0=================================0
# | Kernel Point Convolutions |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Class handling the visualization
#
# ----------------... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
print "Error: sugar.activity.Bundlebuilder not found."
|
"""
Support for monitoring if a sensor value is below/above a threshold.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.threshold/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
... |
class LocustError(Exception):
pass
class ResponseError(Exception):
pass
class CatchResponseError(Exception):
pass
class MissingWaitTimeError(LocustError):
pass
class InterruptTaskSet(Exception):
"""
Exception that will interrupt a Locust when thrown inside a task
"""
def __init_... |
#
# 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 ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from .APIKeyLabel import APIKeyLabel
from .AddApiKeyReqBody import AddApiKeyReqBody
from .AddIncludeSubOrgsOfReqBody import AddIncludeSubOrgsOfReqBody
from .AddOrganizationMemberReqBody import AddOrganizationMemberReqBody
from .Address imp... |
import torch.nn as nn
from models.blocks import GlobalAvgPool2d
class _VanillaConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size):
super(_VanillaConvBlock, self).__init__()
self._block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size, str... |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import re
import six
from azure.core.credentials import AzureKeyCredential
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
from azure.c... |
from direct.distributed.ClockDelta import *
from direct.interval.IntervalGlobal import *
from toontown.building.ElevatorConstants import *
from toontown.building.ElevatorUtils import *
from toontown.building import DistributedElevatorExt
from toontown.building import DistributedElevator
from toontown.toonbase import To... |
"""
Multi-level Context Matching code
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
from . rnn import RNNEncoder, max_along_time, mean_along_time
from . modules import ContextMatching
class MCM(BaseModel):
def __init__(self, pt_emb, **kwargs):
super().... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
#
# 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 ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
import json
import argparse
app = Flask(__name__)
def get_args_parser():
parser = argparse.ArgumentParser(description='http-service')
parser.add_argument('-p', '--port', default=8080, type=int, help='监听端口')
return parser.parse_args(... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
import logging
from collections import Counter
from pathlib import Path
from time import time, sleep
from typing import List
from blspy import G1Element
from chiapos import Verifier
from covid.plotting.manager import PlotManager
from covid.plotting.util import (
PlotRefreshResult,
PlotsRefreshParameter,
g... |
# Copyright (C) 2009 by Eric Talevich (eric.talevich@gmail.com)
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Base classes f... |
import logging
from collections import defaultdict
import numpy as np
import pandas as pd
from .stacker_ensemble_model import StackerEnsembleModel
from ..greedy_ensemble.greedy_weighted_ensemble_model import GreedyWeightedEnsembleModel
logger = logging.getLogger(__name__)
# TODO: v0.1 see if this can be removed an... |
# -*- coding: utf-8 -*-
"""TFJS_Week3_Exercise.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1J7L7quVCBtJfE7lUpKejqwZ2L2dmkVAC
"""
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in com... |
#!/usr/bin/env python3
# Copyright (c) 2015-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 preciousblock RPC."""
from test_framework.test_framework import BitcoinTestFramework
from tes... |
#
# 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 ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create planes
# Create the RenderWindow, Renderer
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer( ren )
iren = vtk.vtkRenderWindowInteractor()
iren.Set... |
import uuid
import numpy
import xxhash
import judo
from judo.judo_backend import Backend
class Hasher:
def __init__(self, seed: int = 0):
self._seed = seed
@property
def uses_true_hash(self) -> bool:
return Backend.use_true_hash()
@staticmethod
def hash_numpy(x: numpy.ndarray) ... |
#-*- coding:utf-8 -*-
import pandas as pd
filename = '../subset/classifision_data.xls'
data = pd.read_excel(filename)
r = data[[u'聚类类别']]
data = data[['R','F','M','C','L']]
out_fig = '../figures/'
def fig_plot(data,title): #自定义作图函数
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
p... |
import asyncio
import aiohttp
import bs4
import pandas as pd
import json
from datetime import datetime
import csv
class Main:
"""
Get real time quotes on Fortune 100 companies or whatever tickers populate symlist.csv.
Output data points to MS SQL-Server
"""
# Without headers and params the webp... |
# -*- coding: utf-8 -*-
import functools
import sys
from argparse import ArgumentParser
import tensorflow as tf
from pprint import pformat
from tensorflow.contrib.framework import arg_scope
import tfsnippet as spt
from tfsnippet.examples.utils import MLResults, MultiGPU, print_with_title
class ExpConfig(spt.Config)... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Tftp(A10BaseClass):
"""Class Description::
DS-Lite TFTP ALG (default: disabled).
Class tftp supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param tftp_enable: {"... |
from pynput.mouse import Button, Controller
from time import sleep
class Mouse:
def __init__(self, sleep=0):
self.mouse = Controller()
self.sleep = sleep
def get_position(self):
sleep(self.sleep)
return self.mouse.position
def set_position(self, x: int, y: int):
s... |
#!/usr/bin/env python3
# vim: set fenc=utf8 ts=4 sw=4 et :
import sys
import socket
import random
from threading import Thread
with open("key.png", "rb") as f:
SECRET = f.read()
def client_thread(clientsocket):
random.seed()
clientsocket.send(bytes([
SECRET[i] ^ random.getrandbits(8)
for ... |
import numpy as np
from seisig import*
def create_timewedgeModel(seismic, model, dtc, Theta, Beta, tBottom, tTop, wedgeAngle, Q=False):
print('\n\n Cálculos del modelo de cuña sintético\n\n')
FreqVel = model.vp[0]
for z in range(seismic.zLen):
print(('CDP #{} de {}').format(z+1, seismic.zLen))
... |
"""
filename: test_routes.py
description: Tests for Routes.
created by: Omar De La Hoz (oed7416@rit.edu)
created on: 11/05/18
"""
import pytest
import config
from app import app
class TestRoutes(object):
@classmethod
def setup_class(self):
self.app = app.test_client()
app.config['DEBUG'] = Fal... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
@author: Javier Espinosa
@contact: javier.espinosa@sciops.esa.int
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 13 Jan. 2021
"""
import tempfile
import os
import pytest
from astroquery.esa.hubble import ESAHubble
... |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... |
# qubit number=3
# total number=2
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collection... |
# coding: utf-8
from __future__ import absolute_import, print_function
import base64
import os
import subprocess
import unittest
from pprint import pprint
from time import sleep
import docusign_esign as docusign
from docusign_esign import AuthenticationApi, EnvelopesApi, TemplatesApi, DiagnosticsApi, FoldersApi, Api... |
from sqlalchemy import orm
from alchy import query
from tests.base import TestQueryBase
from tests.fixtures import Foo, Bar, Baz, Qux
class TestQuery(TestQueryBase):
def test_session_query_class(self):
"""It should be the default class type for Manager session queries"""
self.assertIsInstance(... |
import re
import sys
import scapy.all as scapy
import os
import time as t
import socket
import colorama
import psutil
from colorama import Fore
from colorama import init
import datetime
import pyfiglet
from datetime import datetime
import subprocess
from os import system
from sys import stdout
init()
def os... |
# -*- coding: utf-8 -*-
# See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import os
import shutil
import sys
from django.conf import settings
from django.http impo... |
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model
dataset_size = 1498
codes = []
path = 'encoder/rose'
for id in range(dataset_size):
code = np.loadtxt(path+'{:04d}.txt'.format(id))
codes.append(code)
#code = np.loadtxt(path+'{:04d}v.txt'.format(id))
#codes.ap... |
import collections
import logging
import re
import urllib.parse
from mopidy import backend, models
from mopidy.models import SearchResult, Track
logger = logging.getLogger(__name__)
def generate_uri(path):
return f"soundcloud:directory:{urllib.parse.quote('/'.join(path))}"
def new_folder(name, path):
retu... |
#!/usr/bin/python
#_*_ coding: utf-8 _*_
'''
@file get-zrh.2.py
@brief download arrivals and departures from ZRH (Airport Zurich)
@author Simon Burkhardt - simonmartin.ch - github.com/mnemocron
@date 2017-07-14
@description made for use with Python 2.7.9
@bug It seems like the last few flights appear t... |
# Generated by Django 2.1 on 2019-08-29 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestion', '0012_auto_20190827_2119'),
]
operations = [
migrations.AddField(
model_name='historicalproduct',
name='use_... |
# first images year
L4_start = 1982
# max year for land cover
land_cover_max_year = 2019
sensor_max_year = 2020
land_cover_first_year = 1992
# name of the sensor, GEE asset
sensors = {
"Landsat 4": ["LANDSAT/LT04/C01/T1_SR", 30, "l4"],
"Landsat 5": ["LANDSAT/LT05/C01/T1_SR", 30, "l5"],
"Landsat 7": ["LAN... |
#!/usr/bin/python2.4
#
# 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... |
import json
import os.path
class Config:
DEFAULT_CONFIG = {
"SERVER_URL": "WARGAME.labs.overthewire.org",
"SERVER_PORT": 2220,
"USERNAME_FORMAT": "WARGAME{}",
"DEFAULT_LEVEL": 0,
}
def __init__(self, filename):
self.filename = filename
self.config = self.DEFAULT_CONFIG
def load(self):
if not os.pa... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
from typing import List
from boa3.builtin import public
@public
def Main(operation: str, args: List[int]) -> int:
if len(args) < 2:
return 0
a: int = args[0]
b: int = args[1]
c: int
if a < b:
c = Add(a, b)
elif a <= 0 and b <= 0:
c = Sub(a, b)
else:
c = 0
... |
import torch
import torch.nn as nn
from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler
from .. import builder
from ..registry import DETECTORS
from .base import BaseDetector
from .test_mixins import BBoxTestMixin, MaskTestMixin, RPNTestMixin
@DETECTORS.register_module
class TwoStageDetector(B... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(C) 2001 - 2014 SUZUKI Hisao, Mitko Haralanov, Łukasz Langa
# 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, incl... |
#!/usr/bin/env python
# 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 ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
# 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... |
from collections import ChainMap
from datetime import datetime, timezone
from fcache.cache import FileCache
from UnleashClient.api import send_metrics
from UnleashClient.constants import METRIC_LAST_SENT_TIME
def aggregate_and_send_metrics(url: str,
app_name: str,
... |
"""
The :mod:`tslearn.datasets` module provides simplified access to standard time series datasets.
"""
import numpy
import zipfile
import os
import csv
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
from tslearn.utils import to_time_series_dataset
__author__ =... |
def somar(x,y):
return x + y
def subtrair (x,y):
return x-y
def mult ():
pass |
import pandas as pd
import matplotlib.pylab as pl
import matplotlib.patches as patches
names = (
'age',
'workclass',#Private, Self-emp-not-inc, Self-emp-inc,Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
'fnlwgt',# "weight" of that person in the dataset (i.e. how many people does that pe... |
from invoke import task
from tasks.util.aws_infra import get_sqs_info, get_security_group_ids, get_private_subnet_ids, get_elasticache_url
from tasks.util.config import get_faasm_config
from tasks.util.env import FAASM_CONFIG_FILE
@task
def create(ctx):
"""
Set up skeleton Faasm config
"""
get_faasm_... |
#!/Users/jennysheng/anaconda3/envs/tools/bin/python
import sys
import os
import glob
import numpy as np
import pandas as pd
import gzip
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import curve_fit
import itertools
from collections import Counter
from Bio.Seq import Seq
class mutations:... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from app import ser
# Envoyer un message à l'Arduino pour
# lancer l'animation de la LED voulu
def playAnimation(animationId):
ser.write(str(animationId))
# Main
def main():
print "".join([
"\033[93m", "Component: ",
"\033[94m", "LED",
"\... |
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec
import argparse
import matplotlib
from plot_extinction import plot_ext_stack
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--png", help="save figure as a png file", action="store_true")
parser.ad... |
#!/usr/bin/env python3
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import argparse
import cProfile
import json
import multiprocessing as mp
import os
import re
import wandb
import numpy as np
from PIL import Image
from pgpelib import PGPE
from utils import (img2arr, arr2i... |
import io
import os
from os.path import join as pjoin
import re
import shutil
import tempfile
import urllib.request
import zipfile
from contextlib import closing
from urllib.parse import urlparse
import requests
from nbconvert import SlidesExporter, HTMLExporter
def _get_relative_file_location(url, prefix = 'ext/'):... |
"""
Module providing a percentile function analogous to the functions provided by
scipy.ndimage.measurements.
"""
import numpy as np
def _safely_castable_to_int(dt):
"""Test whether the numpy data type `dt` can be safely cast to an int."""
int_size = np.dtype(int).itemsize
safe = (np.issubdtype(dt, np.si... |
# -*- coding: utf-8 -*-
import codecs
import os.path
from configparser import SafeConfigParser
from serieswatcher.const import *
class Config(object):
"""Singleton to handle the configuration file and use
it in the all program.
"""
config = {}
_instance = None
def __new__(cls):
if cl... |
# qubit number=2
# total number=9
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as... |
from typing import Any, Dict, List, Optional
class SqlValue:
format: str = '{sql}'
def __init__(
self, value: Any, bindings: Optional[List[Any]] = None, **kwargs: Any,
):
self.value: Any = value
self.bindings: Optional[List[Any]] = bindings
self.kwargs: Dict[str, Any] = kw... |
import random
from typing import Dict, List, Any, Tuple
import numpy as np
from mlagents_envs.base_env import (
ActionSpec,
ObservationSpec,
ObservationType,
ActionTuple,
BaseEnv,
BehaviorSpec,
DecisionSteps,
TerminalSteps,
BehaviorMapping,
)
from mlagents_envs.tests.test_rpc_utils ... |
#!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = \
'''The program reads one or more input FASTA files.
For each file it computes a variety of statistics, and then
prints a summary of the statistics as output.
The goal is to provide a solid foundation for new bioinformatics command line tools... |
# Copyright 2017 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PDF tabular data extraction
Based on:
https://github.com/WZBSocialScienceCenter/pdftabextract
WZBSocialScienceCenter/pdftabextract is licensed under the Apache License 2.0
Modified by AnttiHaerkoenen
"""
import fire
import numpy as np
import ocr_tools
def extract... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "${prefix}/include".split(';') if "${prefix}/include" != "" else []
PROJECT_CATKIN_DEPENDS = "actionlib_msgs;geometry_msgs;sensor_msgs;message_runtime;std_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WI... |
delete_project_membership_json = {
"$schema": "http://json-schema.org/draft-06/schema#",
"$ref": "#/definitions/DeleteProjectMembership",
"definitions": {
"DeleteProjectMembership": {
"type": "object",
"additionalProperties": False,
"properties": {
... |
# dragdrop.py
import template
# configure errors for when single value cells are already filled, etc.
class SourceDragManager(): #to be used on source widget
'''This is basically a binding manager for the file-import Treeview. It defines a quasi "drag-and-drop" protocol
that allows the user to copy data heade... |
#!/usr/bin/env python3
import json
import os
import subprocess
import time
import numpy as np
import unittest
from collections import Counter
from pathlib import Path
from cereal import car
import cereal.messaging as messaging
from cereal.services import service_list
from common.basedir import BASEDIR
from common.time... |
# --- HACK: Allow the example to run standalone as specified by a file in the repo (rather than only through the module)
if __name__ == '__main__' and __package__ is None:
import sys; import os; sys.path.append(os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expandus... |
"""Stochastic optimization methods for MLP
"""
# Authors: Jiyuan Qian <jq401@nyu.edu>
# License: BSD 3 clause
import numpy as np
class BaseOptimizer:
"""Base (Stochastic) gradient descent optimizer
Parameters
----------
params : list, length = len(coefs_) + len(intercepts_)
The concatenated... |
import _plotly_utils.basevalidators
class ScopeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="scope", parent_name="layout.geo", **kwargs):
super(ScopeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch.nn.parallel._functions import _get_stream
def scatter(input, devices, streams=None):
"""Scatters tensor across multiple GPUs."""
if streams is None:
streams = [None] * len(devices)
if isinstance(input, list):
if hasat... |
import os
import shutil
import itertools
import configparser
from conans import ConanFile, tools, __version__ as conan_version, RunEnvironment
from conans.errors import ConanInvalidConfiguration
from conans.model import Generator
from conans.tools import Version
class qt(Generator):
@property
def filename(se... |
# $Id: sk.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: Miroslav Vasko <zemiak@zoznam.sk>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.