text stringlengths 2 999k |
|---|
from datetime import date
from ..core import IslamoWesternCalendar, SAT, SUN
from ..registry_tools import iso_register
@iso_register("NG")
class Nigeria(IslamoWesternCalendar):
"Nigeria"
# Civil holidays
include_labour_day = True
labour_day_label = "Workers' Day"
# Christian holidays
includ... |
import copy
from pydantic import Field
import datetime
from typing import (
ClassVar,
Dict,
List,
Optional,
)
from smaregipy import config
from smaregipy import entities
from smaregipy.exceptions import ResponseException
from smaregipy.base_api import (
BaseServiceRecordApi,
BaseServiceCollecti... |
import argparse
import numpy as np
import json
import torch
from torchvision import datasets, transforms
from _params import add_common_params, add_decentralized_params
from _train_utils import test, plot_learning_curve
from _node import Node
from _byzantine_node import ByzantineNode
from _data_utils import default_t... |
import logging
from localstack.config import PORT_STEPFUNCTIONS
from localstack.services import install
from localstack.utils.aws import aws_stack
from localstack.constants import DEFAULT_PORT_STEPFUNCTIONS_BACKEND, TEST_AWS_ACCOUNT_ID, DEFAULT_REGION
from localstack.services.infra import get_service_protocol, start_pr... |
### AGENDA
import os
class Agenda:
# Construtor
def __init__(self):
self.contatos = dict()
self.size = 0
pass
pass
# ToString
def __str__(self):
return str(self.contatos)
def addContato(self, nome, numero):
if nome in self.contatos:
self.c... |
CTAP2_OK = b'\x00' # Indicates successful response.
CTAP1_ERR_INVALID_LENGTH = b'\x03' # Invalid message or item length.
CTAP2_ERR_CBOR_UNEXPECTED_TYPE = b'\x11' # Invalid/unexpected CBOR error.
CTAP2_ERR_MISSING_PARAMETER = b'\x14' # Missing non-optional param... |
"""
Test for file IO.
It tests the results of an optimal control problem with torque_driven_with_contact problem type regarding the proper functioning of :
- the maximize/minimize_predicted_height_CoM objective
- the contact_forces_inequality constraint
- the non_slipping constraint
"""
import importlib.util
from pathl... |
import numpy as np
import xlwings as xw
# from functools import reduce
pi=0.1
#连接到excel
workbook = xw.Book(r'E:/基尼系数测度数据.xlsx')
sheet_names=[workbook.sheets[i].name for i in range(0,len(workbook.sheets),1)]
rng=workbook.sheets[0].range('A1').expand()
nrows=rng.rows.count-1
ncols=rng.columns.count-1
alpha='ABCDEFGHIJKL... |
class InvalidSquadObject(Exception):
pass
class InvalidReportOutput(Exception):
pass
class InvalidReportTemplate(Exception):
pass
class InvalidSquadLookup(Exception):
pass
|
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all,-execution,-papermill,-trusted
# formats: ipynb,py//py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# ... |
import logging
import time
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.INFO,
)
logger = logging.getLogger("Main")
import os,random
import numpy as np
import torch
from utils_glue import output_modes, processors
from pyt... |
# -*- coding: utf-8 -*-
from tests.base import PlivoResourceTestCase
from tests.decorators import with_response
uuid = '4d04c52e-cea3-4458-bbdb-0bfc314ee7cd'
class CallTest(PlivoResourceTestCase):
@with_response(503)
@with_response(503)
@with_response(201)
def test_create(self):
self.client.... |
#!/usr/bin/env python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.autograd import Variable
from tensorboardX import SummaryWriter
import argparse, os, sys, subprocess
import setproctitle, colorama
import numpy as np
from tqdm import tqdm
from glob import glob
from os.path imp... |
# -*- coding: utf-8 -*-
# Copyright © 2019 Damir Jelić <poljar@termina.org.uk>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PR... |
"""
Advanced Test: Rate v/s Range test under various combinations: NAT Mode
pytest -m "throughput_benchmark_test and nat" -s -vvv --skip-testrail --testbed=basic-01
"""
import os
import time
import pytest
import allure
pytestmark = [pytest.mark.ratevsrange, pytest.mark.nat ,pytest.mark.usefixtures("setup_... |
import traceback
import logging
import pkg_resources
from sqlalchemy.exc import SQLAlchemyError
from dispatch.plugins.base import plugins, register
logger = logging.getLogger(__name__)
# Plugin endpoints should determine authentication # TODO allow them to specify (kglisson)
def install_plugin_events(api):
"""... |
# Generated by Django 3.0.5 on 2020-04-03 10:07
import core.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_recipe'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='image',
... |
# -*- coding: utf-8 -*-
"""
@Time: 2021/7/30 20:24
@Author: zzhang zzhang@cenboomh.com
@File: tree_node_name.py
@desc:
"""
from collect.service_imp.result_handlers.result_handler import ResultHandler
from collect.utils.collect_utils import get_safe_data
class TreeNodeName(ResultHandler):
def handler(self, result,... |
from sys import stdin
def funcion(l):
for i in range(1, len(l)):
k = l[i]
j = i
while j > 0 and l[j-1] < k:
l[j] = l[j-1]
j = j-1
l[j] = k
for x in range(len(l[0:10])):
l[x] = str(l[x])
print(','.join(l[0:10]))
l = list(map(int,stdin.read... |
"""
--- Day 15: Chiton ---
You've almost reached the exit of the cave, but the walls are getting closer together. Your
submarine can barely still fit, though; the main problem is that the walls of the cave are covered
in chitons, and it would be best not to bump any of them.
The cavern is large, but has a very low ce... |
send_message_schema = {
'request_schema': {
'type': 'object',
'properties': {
'user_id': {'type': 'integer'},
'message': {'type': 'string'},
},
'required': [
'user_id',
'message',
],
}
}
send_message_to_all_schema = {
'... |
# 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... |
import unittest
from discrete_probability.concept.random_variable import RandomVariable, SetOfRandomVariable, Assignment, Conditional
from discrete_probability.concept.event import Event
class RandomVariableTestCase(unittest.TestCase):
def test_name(self):
name = 'A'
self.assertEqual(RandomVaria... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 requ... |
#%%
import numpy as np
import pandas as pd
import diaux.viz
import arviz as az
import cmdstanpy
import altair as alt
from altair_saver import save
colors, _ = diaux.viz.altair_style()
alt.data_transformers.disable_max_rows()
# Define constants of the experiment
DATE = '2021-02-25'
STRAIN = 'NCM3722'
CONDITION = '... |
"""
Description: This file contains the tools necessary for exploring the parameter space of the LDA model on the HPC.
"""
from multiprocessing import Pool
import csv
import time
import sys
import mpi4py
from ast import literal_eval
"""
Description: This function builds a list of all the possible combinations of the p... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: project_config.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import ... |
# Django settings for tenant_tutorial project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'tenant_schemas.postgresql_backend', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
... |
# Copyright 2019 Alibaba Cloud Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
SECRET_KEY = '1%m#fx+rht9h%ojl+-3()xxg#^&$*8-k8bmq3p8$olgx7iz*5g'
ROOT_URLCONF = 'test_app.urls'
STATIC_URL = ... |
from collections import deque
from typing import Dict, Set, Deque, List
from sc2.position import Point2
from sharpy.events import UnitDestroyedEvent
from sharpy.managers import ManagerBase
from sc2 import UnitTypeId
from sc2.unit import Unit
from sc2.units import Units
MAX_SNAPSHOTS_PER_UNIT = 10
class MemoryManage... |
from typing import Tuple
from ..model import (
Board,
HexInt,
IntegerList,
IRQChip,
JailhouseConfig,
PlatformInfo,
PlatformInfoArm,
)
from ..utils.logging import getLogger
from .passes import BasePass
class TransferBoardInfoPass(BasePass):
def __init__(self) -> None:
self.logg... |
## Project: 3
# Encryption using Dictionary
# i will develop my script by adding decrypthion key mother fuckers حطور الكود بتاعي من التشفير الى فك التشفير
keys = {
"A":"E", "B":"F", "C":"G", "D":"H", "E":"I",
"F":"J", "G":"K", "H":"L", "I":"M", "J":"N",
"K":"O", "L":"P", "M":"Q", "N":"R", "O":"S",
"P":... |
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.distributions import Normal
from torch import distributions
from torch.nn.parameter import Parameter
from torch_geometric.nn import GCNConv, GATConv
from sklearn import cluster, datasets, mixture
from sklearn.preprocessing... |
#Given a vcf and a panel file, export a frequency file with N+5 columns and M+1 rows
# N populations and M SNPs - one header row and the first 5 columns are
#SNPID, CHR, POS, REF, alter_code1
from __future__ import division, print_function
from collections import defaultdict
import argparse, sys
import pdb
########... |
import hashlib
import copy
import logging
import os
import os.path as osp
import sys
cur_dir = osp.dirname(osp.abspath(__file__))
PROJ_ROOT = osp.normpath(osp.join(cur_dir, "../../.."))
sys.path.insert(0, PROJ_ROOT)
import time
from collections import OrderedDict
import mmcv
import numpy as np
from tqdm import tqdm
fr... |
"""Trains a ResNet on the CIFAR10 dataset.
ResNet v1
[a] Deep Residual Learning for Image Recognition
https://arxiv.org/pdf/1512.03385.pdf
ResNet v2
[b] Identity Mappings in Deep Residual Networks
https://arxiv.org/pdf/1603.05027.pdf
"""
from __future__ import print_function
import keras
from keras.layers import Den... |
### Types to hold CTR's data
class catboost_model_ctr(object):
def __init__(self, base_hash, base_ctr_type, target_border_idx, prior_num, prior_denom, shift, scale):
self.base_hash = base_hash
self.base_ctr_type = base_ctr_type
self.target_border_idx = target_border_idx
self.prior_n... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsFeatureSource.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
... |
import YOUR_PACKAGE
if __name__ == "__main__":
print(f"Running Package:\n\t{YOUR_PACKAGE.__name__}")
|
# Copyright 2019 Cloudera, 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, s... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "caipirinha.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
import distutils.version
try:
import greenlet
getcurrent = greenlet.greenlet.getcurrent
GreenletExit = greenlet.greenlet.GreenletExit
preserves_excinfo = (distutils.version.LooseVersion(greenlet.__version__)
>= distutils.version.LooseVersion('0.3.2'))
greenlet = greenlet.greenlet
except... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) IBM Corporation 2019
#
# 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
#
# U... |
"""Generators for drawing data from statistical distributions."""
import numpy as np
###################################################################################################
###################################################################################################
def poisson_train(frequency, dur... |
#
# Generated with VariableFieldBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from .parameterfield import ParameterFieldBlueprint
class VariableFi... |
from dataclasses import dataclass, field
from itertools import accumulate
from typing import Tuple, Set
from veniq.ast_framework import ASTNode
Statement = ASTNode
@dataclass
class StatementSemantic:
used_objects: Set[str] = field(default_factory=set)
used_methods: Set[str] = field(default_factory=set)
... |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... |
import numpy as np
import pandas as pd
from scipy import stats
import tensorflow as tf
### TFRecords Functions ###
def _float_feature(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _int64_feature(value):
"""Returns an int6... |
# -*- coding: utf-8 -*-
import numpy as np
from numba import njit, prange
from numpy import ndarray, pi as PI
from dewloosh.math import squeeze
from dewloosh.math.array import atleast3d
@squeeze(True)
def lhs_Navier(size: tuple, shape: tuple, *args, D: ndarray,
S: ndarray = None, model: str = 'mindlin... |
# Copyright 2019 Province of British Columbia
#
# 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... |
import pandas as pd
from pyecharts.charts import Radar
from pyecharts import options as opts
from pyecharts.globals import CurrentConfig,ThemeType
df = pd.read_excel('real_estate_info.xlsx')['规划用途']
datas = df.value_counts()
items = datas.index.tolist()
colors = ['#FF0000', '#FF4500', '#00FA9A', '#FFFFF0', '#FFD700']
... |
#!/usr/bin/env python3
#import chardet
import sys
def readline_safe():
line = None
while line == None:
try:
line = sys.stdin.readline()
except:
pass
return line
def main():
line = readline_safe()
while line:
if not line.startswith('CVE-') or line.sp... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
from collections import deque
import sys
sys.setrecursionlimit(1000000)
#INF = 1001001001
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]
H, W = map(int, input().split())
S = [input() for _ in range(H)]
#ans = 0
q = deque([])
dist = [['False'] * W for _ in range(H)]
for si in range(H):
for sj in range(W):
if S[si][... |
from pyplan.pyplan.common.baseService import BaseService
from pyplan.pyplan.usercompanies.models import UserCompany
from .models import Activity, ActivityType
from django.conf import settings
import os
class ActivityService(BaseService):
def registerOpenModel(self, file):
self.client_session.userCompanyI... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
'''
Base class for sqlalchemy
'''
__author__ = 'Elisha Yadgaran'
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, DateTime, func
from sqlalchemy_mixins import AllFeaturesMixin
Base = declarative_base()
class BaseSQLAlchemy(Base, AllFeaturesMixin):
'''
Base class for ... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
#
# Author Yann Bayle
# E-mail bayle.yann@live.fr
# License MIT
# Created 01/12/2016
# Updated 01/12/2016
# Version 1.0.0
#
"""
Description of bayle.py
======================
0 Input the local extracted features from YAAFE
13 MFCC per frame
186 musical p... |
def bezout(a, b):
"""returns u, v such as au+bv = pgcd(a,b)"""
if b == 0:
return (1, 0)
else:
(u, v) = bezout(b, a % b)
return (v, u - (a // b) * v)
def chinese_theorem_inv(modulo_list):
"""
Returns (x, n1*...*nk) such as
x mod mk = ak for all k, with
modulo_list =... |
# import necessary packages
from selenium import webdriver
import pyttsx3 as p
# class to see the information
class IMDBlatestBestMovies():
def __init__(self):
self.driver = webdriver.Chrome(executable_path=r"C:\Users\mtiwari33\Downloads\Softwares\chromedriver_win32\chromedriver")
def recommend(self):... |
from django.core.management.base import BaseCommand, CommandError
from newspaper2.news.models import News
class Command(BaseCommand):
help = 'Count news.'
def handle(self, *args, **options):
print(News.objects.count()) |
# coding: utf-8
# AUTOGENERATED BY gen_script.sh from kpony4.py
# Copyright (C) Nyimbi Odero, Sun May 21 04:14:11 EAT 2017
import calendar
from flask import redirect, flash, url_for, Markup
from flask import render_template
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.view... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
'''Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status,
de acordo com a tabela abaixo:
- IMC abaixo de 18,5: Abaixo do Peso
- Entre 18,5 e 25: Peso Ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida'''
print (... |
import os
import pytest
from azure.communication.phonenumbers.aio import PhoneNumbersClient
from _shared.asynctestcase import AsyncCommunicationTestCase
from _shared.testcase import ResponseReplacerProcessor, BodyReplacerProcessor
from _shared.utils import create_token_credential
from azure.communication.phonenumbers i... |
import sys
from time import sleep, time
import dask
import pytest
from dask.distributed import Client
from dask_jobqueue import MoabCluster, PBSCluster
from . import QUEUE_WAIT
@pytest.mark.parametrize("Cluster", [PBSCluster, MoabCluster])
def test_header(Cluster):
with Cluster(
walltime="00:02:00", pr... |
import sublime
import os
import sys
DEBUG = None
def set_log_level(log_level):
global DEBUG
DEBUG = log_level
def log_debug(line):
"""
Write debug output, if enabled, to stdout (Sublime console)
"""
global DEBUG
if DEBUG:
sys.stdout.write(line + "\n")
sys.stdout.flus... |
import re
import pickle
import matplotlib.pyplot as plt
from icd9cms.icd9 import search
with open("../data/pcode_dict.txt", "rb") as fp:
icd9_pcode_dict = pickle.load(fp)
def plot_scores(score_df, model, bins=100, ft='X_scores'):
#rng = [score_df[ft].min(), score_df[ft].mean() + 2*score_df[ft].std()]
... |
#!/usr/bin/env python
from iris_sdk.models.maps.base_map import BaseMap
class DldaTnGroupsMap(BaseMap):
dlda_tn_group = None |
import numpy as np
import scipy.sparse as sp
import copy
import autograd.numpy as npa
import matplotlib.pylab as plt
from autograd.extend import primitive, vspace, defvjp, defjvp
""" Useful functions """
""" ==================== SPARSE MATRIX UTILITIES ==================== """
def make_sparse(entries, indices, shap... |
import RPi.GPIO as GPIO
import math
import os
from datetime import datetime
from time import sleep
# This is for revision 1 of the Raspberry Pi, Model B
# This pin is also referred to as GPIO23
INPUT_WIRE = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(INPUT_WIRE, GPIO.IN)
while True:
value = 1
# Loop until we read... |
import tabulate, sys
buf = open(sys.argv[1], "r", encoding="utf-8").read()
eps = float(sys.argv[2])
blocks = buf.split("./delta_network_test ")
verified_props = {}
total_props = {}
for block in blocks[1:]:
lines = block.strip().split("\n")
prop = int(lines[0].strip().split(" ")[5])
delta_int = list(filter... |
def test (d : int) -> bool:
scope, num = 0, 0
global n, k ,p
i = 0
while i <= n:
scope = p[i] + d
num += 1
if num > k:
return False
if p[n - 1] <= scope and num <= n:
return True
while scope <= p[i]:
i += 1
return False
n, ... |
import sys
import os
import json
import time
import tensorflow as tf
from tensorflow.core.protobuf import config_pb2
import parallax
import parallax_config
import configuration
import skip_thoughts_model
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("data_path", None, """Where to training/test data is stored.""... |
from datetime import timedelta
from unittest.mock import Mock, ANY
import pytest
import os
from schema import SchemaError
from kong.config import Config, Notifier, NotificationManager, slurm_schema
def test_config_creation(state):
config = Config({})
def test_attribute_access(state):
config = Config({"exi... |
""" EfficientNet / MobileNetV3 Blocks and Builder
Copyright 2020 Ross Wightman
"""
import re
from copy import deepcopy
from .conv2d_layers import *
from geffnet.activations import *
# Defaults used for Google/Tensorflow training of mobile networks /w RMSprop as per
# papers and TF reference implementations. PT mome... |
#!/usr/bin/env python
# coding=utf8
#
# (C) 2015-2016, MIT License
'''
Installation configuration.
'''
from setuptools import setup
setup(
name='kanaconv',
version='1.0.1',
description=(
'Converts hiragana and katakana to rōmaji according to '
'Modified Hepburn transliteration rules'
)... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import contextlib
from dataclasses import dataclass, fields
from datetime import datetime
import logging
import os.path
from pathlib import Path
import socket
from subprocess import Popen
import sys
import time
from typing import Optional, Tuple,... |
"""
Reimplementations of constructs introduced in later versions of Python than
we support. Also some functions that are needed SymPy-wide and are located
here for easy import.
"""
import operator
from collections import defaultdict
from time import perf_counter as clock
from sympy.external.gmpy import SYMPY_INTS, HA... |
import json
import os
import sys
import pandas as pd
from azureml.core.webservice import AksWebservice
from loguru import logger
sys.path.append(os.getcwd())
import config as f # noqa: E402
# Load test data
data_path = os.path.join('data', 'regression_kaggle_retail_data_analytics',
'process... |
import logging
import os
import shlex
import tempfile
from functools import total_ordering
from typing import (
Any,
cast,
Dict,
Iterable,
Iterator,
KeysView,
List,
Optional,
Sequence,
Tuple,
TYPE_CHECKING,
Union,
)
from galaxy import exceptions
from galaxy.model import ... |
import numpy as np
import sys
import matplotlib.pyplot as plt
from metod_alg import objective_functions as mt_obj
def compute_its(x, d, g, args, step_size):
"""
Function to compute iterations of descent where the step length is a
fixed positive constant.
Parameters
----------
x... |
import os
import tempfile
from contextlib import contextmanager
from ..hdl import *
from ..hdl.ast import SignalSet
from ..hdl.xfrm import ValueVisitor, StatementVisitor, LHSGroupFilter
from ._base import BaseProcess
__all__ = ["PyRTLProcess"]
class PyRTLProcess(BaseProcess):
__slots__ = ("is_comb", "runnable"... |
# coding: utf-8
"""
Talend Management Console Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import abs... |
import numpy as np
import os, cv2
imgs = np.load('test_set_ck_extended_no_resize.npy')
lbls = np.load('test_labels_ck_extended_no_resize.npy')
for i in range(imgs.shape[0]):
print (lbls[i])
cv2.imshow('img', imgs[i])
cv2.waitKey(0)
|
#!/usr/bin/env python3
# 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.
"""
Knowledge retrieval agent.
Used in interactive mode when the knowledge is not available. Uses the retrieval model
fr... |
#!/usr/bin/env python3
import os, shutil, subprocess, sys, time
from datetime import datetime
USB_PATH = "/run/media/arebel/2004-1014/DCIM/DCIMA/"
TEMP_USB_PATH = "/home/arebel/videos/recfie/temp/"
UNPROCESSED_PATH = "/home/arebel/videos/recfie/unprocessed/"
FINAL_PATH = "/home/arebel/videos/recfie/final/"
QUEUE_FILE_... |
# 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... |
name = "graphtastic"
|
from abc import ABC
import gym
import numpy as np
import pandas as pd
from gym.spaces import Discrete
from numpy.random.mtrand import RandomState
from scipy.special import expit as sigmoid
from tqdm import trange
from .configuration import Configuration
from .context import DefaultContext
from .features.time import D... |
import json
from aiohttp import web
from aiohttp_boilerplate.logging import view_logger
# Sugar for transfer json message to string
def JSONHTTPError(message, errorClass=None, headers=None):
message = json.dumps(message)
headers = headers or {}
headers['Content-Type'] = 'application/json'
# ToDo
... |
import pyrealtime as prt
class CounterLayer(prt.InputLayer):
def __init__(self, target, *args, **kwargs):
self.target = target
super().__init__(*args, **kwargs)
def generate(self, counter):
if counter == self.target:
# can trigger a shutdown by returning stop signal or cal... |
"""
Imports
"""
import pandas as pd
import warnings
import requests
import json
import os
"""
Main Scripts
"""
## Loading static files
resource_filepath = os.path.join(os.path.dirname(__file__), 'stream_to_resource_id.json')
with open(resource_filepath, 'r') as fp:
stream_to_id_map = json.load(fp)
## Main cla... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
import os
from shutil import copyfile
from tempfile import TemporaryDirectory
import pytest
import genomepy.exceptions
def test_ucscprovider(ucsc):
assert ucsc.name == "UCSC"
assert ucsc.taxid_fields == ["taxId"]
def test__search_accession(ucsc):
assert list(ucsc._search_accession("not_an_id")) == []
... |
# Copyright (c) MONAI Consortium
# 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, so... |
# -*- coding: utf-8 -*-
"""
pyvisa-py.protocols.rpc
~~~~~~~~~~~~~~~~~~~~~~~
Sun RPC version 2 -- RFC1057
This file is drawn from Python's RPC demo, updated for python 3.
XXX There should be separate exceptions for the various reasons why
XXX an RPC can fail, rather than using RuntimeError for... |
# encoding: utf-8
"""
Planetary Data System's Digital Object Identifier service — tests for core inputs
"""
import unittest
from . import input_util_test
from . import pds4_util_test
def suite():
suite = unittest.TestSuite()
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(input_util_test))
... |
from __future__ import absolute_import, division, print_function
import os
import pytest
import numpy as np
from mock import patch, MagicMock
from matplotlib.colors import ColorConverter
from glue import custom_viewer
from glue.tests.helpers import PYSIDE2_INSTALLED # noqa
from glue.core import HubListener, Applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.