text stringlengths 1 927k |
|---|
#!/usr/bin/env python
import os
from shipper import Shipper, run, command
import subprocess
# DOCKER_URL = "/var/run/docker.sock"
DOCKER_HOST = "localhost:4243"
DOCKER_URL = "tcp://127.0.0.1:4243"
s = Shipper([DOCKER_HOST])
def pmk(t):
rootdir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
ret... |
from flask import current_app as app
from typing import Any
import resources.db_utils as db_utils
import sqlite3
import shutil
def get_user_by_id(data: dict) -> Any:
user_id = data["id"]
data = {
"filename": "accounts",
"folder": "server",
"table": "accounts",
"select": "user... |
# -*- coding: utf-8 -*-
from twisted.internet import defer
import re
import base
class BaseXmppParser(base.BaseParser):
def formatResult(self, request, result):
if not isinstance(result, dict):
return 'ERROR. Parser has got a strange shit from handler.'
ok = result.get('ok')
... |
import warnings
import pytest
from matplotlib.testing.decorators import check_figures_equal
@pytest.mark.xfail(
strict=True, reason="testing that warnings fail tests"
)
def test_warn_to_fail():
warnings.warn("This should fail the test")
@pytest.mark.parametrize("a", [1])
@check_figures_equal(extensions=["pn... |
# 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 appli... |
from aiogram.dispatcher.filters.state import StatesGroup, State
class MenuSG(StatesGroup):
main = State()
about = State()
contacts = State()
materials = State()
faq = State()
ask = State() |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from driver.mailoperator import get_new_mails
def index(request):
new_mails = get_new_mails()
template = loader.get_template('driver/index.html')
context = {
'new_mails': new_mails,
}
... |
# Copyright 2021 Northern.tech AS
#
# 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 ag... |
import copy
import logging
import os
import random
import shutil
import sys
import tempfile
import time
from argparse import Namespace
from dataclasses import replace
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple, Any
from blspy import AugSchemeMPL, G1Element, G2Element, PrivateKey
... |
"""
WSGI config for kalachakra project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SE... |
import numpy as np
from unidrnd import unid_rnd
import matplotlib.pyplot as plt
from scipy import stats
plt.rcParams["figure.figsize"]=(10,15)
# 真实的模型参数值
theta = 0.7
# 采样的样本数量
n_samples = [10, 100]
x_label = ['(a)','(b)','(c)','(d)']
for index,n_sample in enumerate(n_samples):
B = 10000 # 重复试验的次数
... |
# Copyright (c) 2019, NVIDIA CORPORATION.
import urllib.parse
from utils import assert_eq
import nvstrings
urls1 = ["http://www.hellow.com", "/home/nvidia/nfs", "123.45 ~ABCDEF"]
urls2 = [
"http://www.hellow.com?k1=acc%C3%A9nted&k2=a%2F/b.c",
"%2Fhome%2fnfs",
"987%20ZYX",
]
def test_encode_url():
... |
#!/usr/bin/env python
import os
import sys
import time
options = {
'l' : False, # Auto loop
'u' : False, # Uglify
}
if len(sys.argv) > 1:
for argv in sys.argv:
if argv in options:
options[argv] = True
def build():
os.system('coffee -b --compile --output js/ coffee/')
if options['u']:
os.chdir('./js')
... |
# Copyright (c) 2012-2016 Seafile Ltd.
import logging
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
import seaserv
from seaserv im... |
# Generated by Django 2.0.2 on 2018-03-01 09:28
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
import users.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
... |
# -*- encoding: utf-8 -*-
'''
@File : configure_data.py
@Time : 2021/01/11 23:28:38
@Author : Ming Ding
@Contact : dm18@mails.tsinghua.edu.cn
'''
# here put the import lib
import os
import ipdb
import sys
import math
import random
from tqdm import tqdm
import copy
import numpy as np
import torch
impor... |
#!/usr/bin/env python
import argparse
import copy
import traceback
from os import listdir
from os.path import isfile, join
#from cv_bridge import CvBridge
import math
import matplotlib.pyplot as plt
import pandas as pd
import random
# u
import numpy as np
import cv2 as cv
import rospy
# Brings in the SimpleAction... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\split_UI.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Split_Dialog(object):
def setupUi(self, Split_Dialog):
S... |
import math
import torch
from . import Sampler
from torch.distributed import get_world_size, get_rank
class DistributedSampler(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In su... |
# !/usr/bin/python
#
# Copyright (C) 2012 Yoav Aviram.
#
# 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 ... |
# Copyright 2015 Google 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 law or a... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
barcode = fields.Char(string='Barcode', help="BarCode", oldname='ean13')
pos_order_count = fields.Integer(
... |
# -*- coding: utf-8 -*-
from datetime import datetime
import json, time, ntpath
def loggedIn(func):
def checkLogin(*args, **kwargs):
if args[0].isLogin:
return func(*args, **kwargs)
else:
args[0].callback.other('You want to call the function, you must login to LINE')
ret... |
#!/usr/bin/env python3
import rospy
import time
import sys
import board
import busio
from sensor_msgs.msg import MagneticField,Imu
from std_msgs.msg import Float64
import qwiic_icm20948
def icm20948_node():
# Initialize ROS node
raw_pub = rospy.Publisher('icm20948/raw', Imu, queue_size=10)
mag_pub = rosp... |
"""
.. module: lemur.plugins.lemur_acme.plugin
:platform: Unix
:synopsis: This module is responsible for communicating with an ACME CA.
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
Snippets from https://raw.githubusercontent.com/alex/let... |
##
# The MIT License (MIT)
#
# Copyright (c) 2016 Stefan Wendler
#
# 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, including without limitation the rights
# to use, copy,... |
from typing import Tuple
import torch
import torch.nn as nn
import kornia
from kornia.filters.kernels import get_laplacian_kernel2d
class Laplacian(nn.Module):
r"""Creates an operator that returns a tensor using a Laplacian filter.
The operator smooths the given tensor with a laplacian kernel by convolving... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import lag_plot
from pandas import datetime
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
df = pd.read_csv("corona2.csv")
df.head(6)
plt.figure()
lag_plot(df['InfectadosDia'], lag... |
from .dummy import DummyClustering
from .position import PositionClustering
from .sliding_hdbscan import SlidingHdbscanClustering
from .sliding_nn import SlidingNNClustering
from .position_and_pca import PositionAndPCAClustering
from .position_ptp_scaled import PositionPTPScaledClustering
clustering_methods = {
"... |
"""
This module implements the `se print_toc` command.
"""
import argparse
import se
from se.se_epub import SeEpub
def print_toc() -> int:
"""
Entry point for `se print-toc`
The meat of this function is broken out into the generate_toc.py module for readability
and maintainability.
"""
parser = argparse.Arg... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader.processors import TakeFirst, Join, MapCompose
from datetime import datetime, timedelta
def comments_strip(string,loader_context):
... |
# encoding: utf-8
from .item import Item
from .mix import ConfigurationMixIn, DeletionMixIn, DescriptionMixIn
class Views(Item):
'''
classdocs
'''
def __init__(self, owner):
'''
Constructor
'''
self.owner = owner
super().__init__(owner.jenkins, owner.url)
... |
"""The tests for numeric state automation."""
from datetime import timedelta
from unittest.mock import patch
import pytest
import voluptuous as vol
import homeassistant.components.automation as automation
from homeassistant.components.automation import numeric_state
from homeassistant.core import Context
from homeass... |
# Copyright 2017-2020 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 "license" fil... |
from .api import * # noqa
from .api import __all__ as api_exports
# Delegate to API export
__all__ = api_exports
# Package metadata
__author__ = 'Tomas Aparicio'
__license__ = 'MIT'
# Current version
__version__ = '1.0.1' |
# 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, software
# d... |
#
# This file is a part of the normalize python library
#
# normalize is free software: you can redistribute it and/or modify
# it under the terms of the MIT License.
#
# normalize is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI... |
# Copyright (c) 2015 Mellanox Technologies, Ltd
# 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
#
# U... |
""" X86 target descriptions and encodings.
See for a reference: http://ref.x86asm.net/coder64.html
"""
from ..generic_instructions import Label, RegisterUseDef
from ..isa import Isa
from ..encoding import Instruction, Operand, Syntax, Constructor, Relocation
from .. import effects
from ...utils.bitfun import wrap_neg... |
"""Test suites for numerical compatibility with librosa"""
import os
import unittest
from distutils.version import StrictVersion
import torch
import torchaudio
import torchaudio.functional as F
from torchaudio._internal.module_utils import is_module_available
LIBROSA_AVAILABLE = is_module_available('librosa')
if LIB... |
from __future__ import absolute_import
import logging
import six
from django.db import transaction
from uuid import uuid4
from sentry.models import OrganizationOption
logger = logging.getLogger("sentry.deletions")
def delete_pending_deletion_option(instance, **kwargs):
if hasattr(instance, "delete_pending_del... |
import time
from os import system
from statistics import stdev
from statistics import variance
import matplotlib as mpl
import matplotlib.pyplot as plt
import W0302
from W0303 import seedList
if __name__ == "__main__":
system("cls")
tStr = str( time.time() )
t = int( tStr[-4:-2])
MDMethSet = W0302.M... |
class UnionFind:
def __init__(self, values):
self.ids = []
self.weights = []
for i, v in enumerate(values):
self.ids.append(v)
def union(self, p, q):
pid = self.ids[p]
qid = self.ids[q]
for i, val in enumerate(self.ids):
if self.ids[i] =... |
import numpy as np
class Deriv:
"""
Calculate the derivative with given order of the function f(t) at point t.
"""
def __init__(self, f, dt, o=1):
"""
Initialize the differentiation solver.
Params:
- f the name of the function object ('def f(t):...')
... |
"""
Utilities that use selenium + chrome headless to save figures
"""
import contextlib
import os
import tempfile
@contextlib.contextmanager
def temporary_filename(**kwargs):
"""Create and clean-up a temporary file
Arguments are the same as those passed to tempfile.mkstemp
We could use tempfile.NamedTe... |
import copy
import gym
from typing import (
Any,
Callable,
Dict,
Optional,
Type,
TYPE_CHECKING,
Union,
)
from ray.rllib.algorithms.callbacks import DefaultCallbacks
from ray.rllib.env.env_context import EnvContext
from ray.rllib.evaluation.collectors.sample_collector import SampleCollector
... |
from fastapi import FastAPI
import pickle
from SatImages import SatImage
import uvicorn
def load_models():
"""
load the models from disk
and put them in a dictionary
Returns:
dict: loaded models
"""
models = {
"knn": pickle.load(open("./model_weights/clf.bin", 'rb'))
}
p... |
import os
import struct
from collections import OrderedDict
from pathlib import PurePath
import numpy as np
import app
from fileio.tif import TIFFile
PRA = {
"Physical Record Type": (1, 1),
"Checksum Type": (2, 2),
"File Number Presence": (5, 1),
"Record Number Presence": (6, 1),
"Parity Error":... |
#Real data cannot be provided for due to patient privacy. We will post a suitable demo example at some point. |
#!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_velpt_ab
@file mi-dataset/mi/dataset/parser/test/test_velpt_ab_dcl.py
@author Chris Goodrich
@brief Test code for the velpt_ab parser
"""
__author__ = 'Chris Goodrich'
from mi.logging import log
import os
import re
from nose.plugins.attrib import attr
... |
import pytest
from icevision.all import *
@pytest.fixture(scope="session")
def fake_faster_rcnn_model():
class FakeFasterRCNNModel(nn.Module):
def __init__(self):
super().__init__()
# hack for the function `model_device` to work
self.layer = nn.Linear(1, 1)
def... |
import re
from django import template
from django.template.loader import render_to_string
register = template.Library()
admin_re = re.compile(r'^admin\/')
def prepopulated_fields_js(context):
"""
Creates a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the a... |
#!/bin/env python3
import argparse
import numpy as np
import pandas as pd
import data_preparation.data_preparation_pos as data_preparation_pos
import fine_tuning
import utils.model_utils as model_utils
import utils.pos_utils as pos_utils
def test(training_lang,
test_lang,
split="test",
sho... |
from pytorch_lightning.utilities.cli import LightningCLI
from pytorch_gleam.data.datasets import KbiMisinfoStanceDataModule
from pytorch_gleam.modeling.models import KbiLanguageModel
if __name__ == '__main__':
cli = LightningCLI(
KbiLanguageModel,
KbiMisinfoStanceDataModule,
run=False,
subclass_mode_model=Tr... |
# 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 use t... |
import datetime
from warnings import warn
from six import raise_from
# In Python 2.7 collections.abc is a part of the collections module.
try:
from collections.abc import Sequence, Set
except ImportError: # pragma: no cover
from collections import Sequence, Set
from flask import current_app
# Older versions... |
import bisect
import time
import numpy as np
import BTrees.OOBTree
from copy import deepcopy
from collections import defaultdict, Counter
from threading import RLock
from functools import reduce
from typing import Text, Dict, List, Set, Tuple, Type
from BTrees.OOBTree import BTree
from appyratus.utils.dict_utils im... |
"""Various helpers to handle config entry and api schema migrations."""
import logging
from aiohue import HueBridgeV2
from aiohue.discovery import is_v2_bridge
from aiohue.v2.models.device import DeviceArchetypes
from aiohue.v2.models.resource import ResourceTypes
from homeassistant import core
from homeassistant.co... |
# flake8: noqa
from sourced.ml.utils.bigartm import install_bigartm
from sourced.ml.utils.pickleable_logger import PickleableLogger |
# Copyright 2014 The Oppia 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 applicable ... |
from tools.utilities import xml_format
class ObjectiveDict(dict):
"""A dictionary describing the objectives for optimization. See self.add_objective()."""
def __init__(self):
super(ObjectiveDict, self).__init__()
self.max_rank = 0
def add_objective(self, name, maximize, tag, meta_func=No... |
from sketch.models import MSLayer
class MSSliceLayer(MSLayer):
"""
Subclass of MSLayer representing a slice in the document.
Although it may have a style attribute, this is never used.
MSSliceLayer has —like MSLayer— a frame property that is an
MSRect which determines its position in the canvas o... |
from torchnlp.tasks.sequence_tagging import Tagger, hparams_tagging_base, VOCABS_FILE
import torch
import torch.nn as nn
import torchtext
from torchtext import data
from torchtext import datasets
import pytest
def udpos_dataset(batch_size):
# Setup fields with batch dimension first
inputs = data.Field(init_... |
#! /usr/bin/env python
# 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, software
... |
class MTAThreadAttribute:
"""
Indicates that the COM threading model for an application is multithreaded apartment (MTA).
MTAThreadAttribute()
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return MTAThreadAttribute()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def __i... |
import asyncio
import functools
import json
import gamla
import pytest
from computation_graph import base_types, composers, graph, run
pytestmark = pytest.mark.asyncio
_ROOT_VALUE = "root"
class _GraphTestError(Exception):
pass
def _node1(arg1):
return f"node1({arg1})"
async def _node1_async(arg1):
... |
import numpy as np
import pytest
import skimage.data as images
from matplotlib.figure import Figure
from skimage import transform as tf
from astropy.coordinates.matrix_utilities import rotation_matrix
from sunpy.image.transform import _rotation_registry, affine_transform
from sunpy.tests.helpers import figure_test
fr... |
# -*- coding: utf-8 -*-
# Natural Language Toolkit: ChrF score
#
# Copyright (C) 2001-2019 NLTK Project
# Authors: Maja Popovic
# Contributors: Liling Tan, Aleš Tamchyna (Memsource)
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
""" ChrF score implementation """
from __future__ import division
fr... |
def distinct_values_bt(bin_tree):
"""Find distinct values in a binary tree."""
distinct = {}
result = []
def _walk(node=None):
if node is None:
return
if node.left is not None:
_walk(node.left)
if distinct.get(node.val):
distinct[node.val] =... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
# test API provided through BaseForecaster
__author__ = ["Markus Löning"]
__all__ = [
"test_raises_not_fitted_error",
"test_score",
"test_predict_time_index",
"test_update_predict_... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_summernote.db',
}
}
MIDDLEWARE_CLASSES = (
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)
STATIC_URL = '/'
ME... |
import pymysql
pymysql.install_as_MySQLdb() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, 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... |
import os
import requests
import json
from . import logger
from .models import Intent, Entity
class ApiAi(object):
"""Interface for making and recieving API-AI requests.
Use the developer access token for managing entities and intents and the client access token for making queries.
"""
def __init_... |
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="size", parent_name="layout.scene.xaxis.title.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_n... |
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['doco... |
import parse_midas_data
#import pylab
import sys
import numpy
import bz2
import calculate_snp_prevalences
################################################################################
#
# Standard header to read in argument information
#
############################################################################... |
import json
from lsassy.log import Logger
class Parser():
def __init__(self, pypydump):
self.pypydump = pypydump
self.log = Logger()
self.credentials = []
def _parse(self, raw=False):
ssps = ['msv_creds', 'wdigest_creds', 'ssp_creds', 'livessp_creds', 'kerberos_creds', 'cr... |
from flask import Flask, escape
app = Flask(__name__)
@app.route('/user/username')
def show_user_profile(username):
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
import face_recognition
import cv2
import numpy as np
from time import sleep
import os,sys
path = './Dataset/'
if len(sys.argv) == 2:
path = sys.argv[1]
files = os.listdir(path)
for name in files:
full_path = os.path.join(path, name)
if os.path.isdir(full_path):
print('Directory: ' + name)
... |
import torch
import numpy as np
import networkx as nx
from torch_geometric.data import InMemoryDataset, Data
class KarateClub(InMemoryDataset):
r"""Zachary's karate club network from the `"An Information Flow Model for
Conflict and Fission in Small Groups"
<http://www1.ind.ku.dk/complexLearning/zachary197... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# StimulusFrontEnd.py
# Copyright (c) 2018, Richard Gerum, Achim Schilling, Hinrich Rahlfs, Matthias Streb
#
# This file is part of ASR-Setup.
#
# ASR-Setup is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... |
from operator import itemgetter
import time
from .websockets import SocketManager
class DepthCache:
def __init__(self, symbol):
"""Intialise the DepthCache
:param symbol: Symbol to create depth cache for
:type symbol: string
"""
self.symbol = symbol
self._bids =... |
#!/usr/bin/env python
"""
Create a dictionary of ascending (sequential) directories.
"""
def make_pathdict(keys, fspath = None):
"""Quickly create a dictionary of ascending path components.
:param keys: list of dictionary keys (base -> root order)
:returns: dictionary of keyed paths
NOTICE: Thi... |
"""
min_max_by_entity
=================
"""
from ansys.dpf.core.dpf_operator import Operator
from ansys.dpf.core.inputs import Input, _Inputs
from ansys.dpf.core.outputs import Output, _Outputs, _modify_output_spec_with_one_type
from ansys.dpf.core.operators.specification import PinSpecification, Specification
"""Oper... |
"""
Tests for salt.utils.jinja
"""
import ast
import itertools
import os
import pprint
import random
import re
import pytest
import salt.config
import salt.loader
# dateutils is needed so that the strftime jinja filter is loaded
import salt.utils.dateutils # pylint: disable=unused-import
import salt.utils.files
imp... |
import uuid
from sqlalchemy.orm import validates
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.schema import FetchedValue
from app.extensions import db
from ....utils.models_mixins import AuditMixin, Base
# FIXME: Model import from outside of its namespace
# This breaks micro-service architecture and... |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Challenge Notebook
# ## Problem: Maximizing XOR
#
# See the [HackerRank problem page](https://www.ha... |
#!/usr/bin/python
import sys
import csv
infile = sys.stdin
#next(infile)
count = 0
for line in infile:
line = line.strip()
my_list = line.split(',') #splitting line based on comma
if(my_list[0] == 'ball'): #checking if the line is a delivery
# print('Hello World')
#print(out)
key_list = my_list[4]+','+my_list[... |
"""
Sequence Labeler Wrapper
"""
import sys
import time
import numpy as np
from copy import deepcopy
from nlp_toolkit.models import Word_RNN, IDCNN, Char_RNN
from nlp_toolkit.trainer import Trainer
from nlp_toolkit.utilities import logger
from nlp_toolkit.sequence import BasicIterator
from nlp_toolkit.data import Data... |
import numpy as np
import pickle
import gzip
import pbp
class PBP_net:
def __init__(self, X_train, y_train, n_hidden, n_epochs = 40,
normalize = False):
"""
Constructor for the class implementing a Bayesian neural network
trained with the probabilistic back propagation ... |
#!/usr/bin/env python
import math
import numpy as np
# f = open('/home/rosuser/catkin_ws/tmp/mapping.log', 'w')
def fprint(s):
return
f.write(s)
f.write('\n')
f.flush()
class Mapping():
def __init__(self, xw, yw, xyreso):
self.width_x = xw*xyreso
self.width_y = yw*xyreso
se... |
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, 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 ... |
# pylint: disable=invalid-name,too-many-function-args,too-many-nested-blocks
"""
Functions that run on executor for measurement.
These functions are responsible for building the tvm module, uploading it to
remote devices, recording the running time costs, and checking the correctness of the output.
"""
import logging... |
"""
Django settings for resumeparser project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import ... |
# Copyright 2012 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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 sys
sys.path.append('../')
import os
from pathlib import Path
import time
import numpy as np
import scipy.optimize
import pickle
from py_diff_pd.common.common import ndarray, create_folder, rpy_to_rotation, rpy_to_rotation_gradient
from py_diff_pd.common.common import print_info, print_ok, print_error, PrettyT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.