content stringlengths 5 1.05M |
|---|
from abc import ABC, abstractmethod
from typing import Dict, Any
import contextvars
from esphome.types import ConfigFragmentType, ID, ConfigPathType
import esphome.config_validation as cv
class FinalValidateConfig(ABC):
@property
@abstractmethod
def data(self) -> Dict[str, Any]:
"""A dictionary t... |
#!/usr/bin/python
# WANT_JSON
DOCUMENTATION = '''
---
module: ini_read
short_description: Reads values from an ini file.
'''
# Example:
# ini_read:
# section: org/gnome/desktop
# option: lock-screen
# path: /etc/dconf/local.d/00-screensaver
from ansible.constants import mk_boolean
from ansible.module_utils.ba... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import enum
class Default:
ENCODING = "utf-8"
class SourceType:
TEXT = "text"
FILE = "file"
URL = "url"
OBJECT = "object"
class TableNameTemplate:
__FORMAT = "%({:s})s"
DEFAULT = __FORMAT.format("default")
FIL... |
"""Simple test scaffold."""
from ds_template import __version__
def test_version():
"""Sample test function."""
assert __version__ == "0.1.0"
|
from Controllers import app
from flask import Flask, request, jsonify, json
import Services.CheckingService as service
#------------------------------------------------------------------------------
# 5.1
# Return C#/.NET type => ''
#------------------------------------------------------------------------------
@app.r... |
from typing import List
from fastapi import APIRouter, Query, Header, HTTPException
from mlad.core import exceptions
from mlad.service.exception import exception_detail
from mlad.service.libs.log import init_logger
from mlad.core.kubernetes import controller as ctlr
router = APIRouter()
logger = init_logger(__name__)... |
from datetime import datetime
import pytest
from pygrocy.data_models.task import TaskCategory
from pygrocy.data_models.user import User
from pygrocy.errors import GrocyError
class TestTasks:
@pytest.mark.vcr
def test_get_tasks_valid(self, grocy):
tasks = grocy.tasks()
assert len(tasks) == 6... |
#!/usr/bin/env python
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# BSD 3-Clause License
#
# Copyright (c) 2021., Redis Labs Modules
# All rights reserved.
#
import yaml
from redisbench_admin.run.common import prepare_benchmark_parameters
from redisbench_admin.run_remote.remote_client import run_remote_benchmark
from redisbench_admin.utils.benchmark_config import extract_benchmar... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import numpy as np
from termcolor import colored
from glob import glob
import zipfile
import time
from .commonutils import TiffReader
class Sentinel2Info(object):
'''
The purpose of this class is to collect useable data from the inpu... |
class Solution:
def isPowerOfTwo(self, n):
# taking adavantage of the fact that binary is base 2 if the MSB is set
# with all other bits cleared then that given number is a power of two
# e.g. with decimal numbers if the most significant digit is 1 followed by
# all other digits being cleared it is a power o... |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozure... |
import pygame
import sys
import random
import os
from time import sleep
# main graphical parameters
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 900
CELL_SIZE = 10
CELL_AMOUNT_X = WINDOW_WIDTH // CELL_SIZE
CELL_AMOUNT_Y = WINDOW_HEIGHT // CELL_SIZE
START_CELL = (1, 1)
GOAL_CELL = (CELL_AMOUNT_X - 2, CELL_AMOUNT_Y - 2)
assert ... |
import time
from itertools import cycle
from typing import List, Optional
from app.services import WindowsInsider
from app.services.logger import Logger
from app.modules.errors import (
DISCORD_COG_LOAD_FAILED,
DISCORD_COG_RELOAD_FAILED
)
from app.config import (
DISCORD_BOT_TOKEN,
DISCORD_BOT_VERSION,... |
from typing import Dict, List, Optional, Union
from pathlib import Path
def parse_cranfield(
data_filepath: Union[str, Path],
site: Optional[str] = None,
network: Optional[str] = None,
inlet: Optional[str] = None,
instrument: Optional[str] = None,
sampling_period: Optional[str] = None,
mea... |
# coding: utf-8
# Distributed under the terms of the MIT License.
""" This file implements some light wrappers to
the Atomic Simulation Environment (ASE).
"""
import copy
from typing import Union
from matador.utils.chem_utils import get_stoich
from matador.utils.cell_utils import get_spacegroup_spg
from matador.crys... |
import mdn_lstm
reload(mdn_lstm)
from collections import OrderedDict
import cPickle as pkl
import sys
import time
import numpy
import theano
from theano import config
import theano.tensor as tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
# Set the random number generators' seeds for c... |
#!/usr/bin/env python
"""Generates a list of hashes of EV certificates found in a log."""
import hashlib
import functools
import pickle
import os
import sys
import ev_metadata
import gflags
from ct.client import scanner
from ct.crypto import cert
from ct.proto import client_pb2
FLAGS = gflags.FLAGS
gflags.DEFINE_i... |
from random import random
from math import sqrt
class Neuronio:
'''
Classe do neurônio de Kohonen, a unidade de processamento é peculiar, portanto difere dos outros neurônios comuns
Temos que passar no construtor, o número de conexões que cada neurônio terá, e será criado vetor dos pesos sinápticos
re... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 GEO Secretariat.
#
# geo-knowledge-hub is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""GEO Knowledge Hub Permission Generators definitions"""
from invenio_records_permissions.generat... |
import os
import timeit
import audlib
from audlib.asr.util import PhonemeMap, CharacterMap, levenshtein
def test_levenshtein():
"""Test edit distance."""
assert levenshtein('', '') == (0, 0, 0, 0)
assert levenshtein('aaa', '') == (3, 3, 0, 0)
assert levenshtein('a', 'aaaaa') == (4, 0, 4, 0)
asser... |
import math
import os
import shutil
from traitlets import Unicode, default
from .base import JobQueueClusterManager, JobQueueStatusTracker
__all__ = ("SlurmClusterManager", "SlurmStatusTracker")
def slurm_format_memory(n):
"""Format memory in bytes for use with slurm."""
if n >= 10 * (1024 ** 3):
... |
'''
Routines implementing the boundary element method.
'''
import cmath
import numpy as np
import scipy as sp
from cnld import abstract, mesh, util
from cnld.compressed_formats import ZFullMatrix, ZHMatrix
from scipy import linalg
from scipy import sparse as sps
from scipy.io import loadmat
@util.memoize
def mem_z_m... |
from .elf import ELF |
import time
import subprocess
from collections import namedtuple,defaultdict
import logging
import json
import os
import yaml
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import threading
def loadTensorBoard(outdir):
t = threading.Thread(target=launchTensorBoard,... |
#!/usr/bin/env python
"""
dgit default configuration manager
[User] section:
* user.name: Name of the user
* user.email: Email address (to be used when needed)
* user.fullname: Full name of the user
"""
import os, sys, json, re, traceback, getpass
try:
from urllib.parse import urlparse
except:
from urlpars... |
#!/usr/bin/env python
#
import unittest
import os
import femagtools.mcv
class McvReaderTest(unittest.TestCase):
def test_read_mcv(self):
testPath = os.path.split(__file__)[0]
if not testPath:
testPath = '.'
filename = "data/TKS_NO_20.MCV"
reader = femagtools.mcv.Reader(... |
import csv
import json
import os
import arrow
from jesse.config import config
from jesse.services.tradingview import tradingview_logs
from jesse.store import store
import jesse.helpers as jh
def store_logs(study_name: str = '', export_json: bool = False, export_tradingview: bool = False, export_csv: bool = False) -... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("func", choices=['init_trading_dates'],
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answ... |
import zaza.openstack.utilities.openstack as openstack_utils
from manilaclient import client as manilaclient
def setup_ganesha_share_type(manila_client=None):
if manila_client is None:
keystone_session = openstack_utils.get_overcloud_keystone_session()
manila_client = manilaclient.Client(
... |
import json
import re
import requests
import spacy
from spacy.symbols import ORTH
from little_helpers import yield_abbr, ABBR_BASE
def get_doc_list(domain, app_name, collection='editions', verbose=True):
""" retrieves a list of doc-uris stored in a dsebaseapp
:param domain: Domain hosting the dsebaseapp ... |
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn import metrics
from joblib import dump, load
def ml_model(criteria_arr):
model = KNeighborsClassifier(n_neighbors= 3)
input_h = 'training.csv'
df = pd.read_csv(input_h, h... |
#!/usr/bin/python3
#Usage: error-handling.py
#Author: David Caballero <d@dcaballero.net>
#Version: 1.0
# division by 0 error
# print(5/0)
# file not found
# file = open("file","r")
# data type error int / string
# int('1.2b')
# int('1.2')
# division by 0 error
# a = 5/0
# print("after error")
try:
a = 5/0
ex... |
class Solution(object):
def canCross(self, stones):
"""
:type stones: List[int]
:rtype: bool
"""
if not stones or (len(stones) > 1 and stones[1] != 1):
return False
# each stone maps to a set of jump lengths that can lead to current stone
dp = {x ... |
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import refresh_jwt_token
from apps.api import views
router = routers.DefaultRouter()
router.register(r'me', views.MyUserDetailV... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from distributor.shared_messages import IconInfoData
from o... |
from p5 import *
import math
import keyboard
class CircleOutline:
def __init__(self, pos, radius, points):
self.pos = pos
self.radius = radius
self.points = points
self.angle = 0
def show(self):
increment = (math.pi * 2) / self.points
for i in range(0, self.poin... |
""" Rules for host and target operating system information.
However, just provides very simple information.
"""
OSInfo = provider(
doc = "Operating system information.",
fields = dict(
is_win = "Is Windows family system",
is_osx = "Is Mac family system",
is_unix = "Is Unix family system... |
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edges_from([("a","b"),("c","d")])
nx.draw(G)
plt.savefig("path.png")
|
"""Contains very basic functions
"""
import os
import shutil
import numpy as np
from pyproj import CRS, Transformer
def get_result_paths(folder_path):
"""Joins results subfolders to ``folder_path`` and returns a dict
Arguments
---------
folder_path : str
Path of scenario run results
Retur... |
import py
from pypy.interpreter.argument import Arguments
from pypy.interpreter.baseobjspace import W_Root, DescrMismatch
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import (interp2app, BuiltinCode, unwrap_spec,
WrappedDefault)
from rpython.rlib.jit import promote
from ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_ME... |
import json
import requests
import time
from urllib import parse
from datetime import datetime
import ac_utility
from ac_constants import *
"""
# The json from Airtable is processed first in build_icandi_json, parsed then saved locally to icandi.json
# icandi.json is then loaded into get_venue_list for process... |
# coding: utf-8
"""XGBoost: eXtreme Gradient Boosting library.
Contributors: https://github.com/dmlc/xgboost/blob/master/CONTRIBUTORS.md
"""
from __future__ import absolute_import
from .core import DMatrix, Booster
from .training import train, cv
from .sklearn import XGBModel, XGBClassifier, XGBRegressor
from .plotti... |
# Write a function to calculate factorial(n)
# How can we calculate how many capital letters are in a string?
|
with open('2015/day_02/list.txt', encoding="utf-8") as f:
lines = f.readlines()
value = 0
for i in range(len(lines)):
a = (lines[i].split('\n')[0]).split('x')
for b in range(len(a)):
a[b] = int(a[b])
a.sort()
value += 2*(int(a[0])+int(a[1])) + int(a[0])*int(a[1])*int(a[2])
print(value) |
host = '47.114.171.118'
port = 32333
db = 'fpyd'
user = 'root'
password = '111111' |
from django.contrib import admin
from .models import Sender
admin.site.register(Sender)
|
import unittest
from unittest.mock import mock_open, patch, MagicMock
from unittest import mock
from src.sample.FriendshipsStorage import FriendshipsStorage
from src.sample.Friendships import Friendships
class TestFriendshipsStorage(unittest.TestCase):
def setUp(self):
self.fs = Friendships()
se... |
#
# PySNMP MIB module ELTEX-PP4 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-PP4
# Produced by pysmi-0.3.4 at Wed May 1 13:02:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
""" The qutip-cupy package provides a CuPy-based data layer for QuTiP. """
# we need to silence this specific warning
# remember to remove once QuTiP moves matplotlib
# to an official optional dependency
import warnings
try:
__import__("cupy")
except ModuleNotFoundError:
raise RuntimeError(
"qutip_cup... |
# Copyright 2013-2022 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)
from spack.package import *
class Byacc(AutotoolsPackage):
"""Berkeley Yacc is an LALR(1) parser generator. Berkele... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from copy import copy
import numpy as np
from nipy.core.image.image import Image, rollaxis
from nipy.core.reference.coordinate_map import CoordinateSystem, \
AffineTransform, compose
class ImageList(... |
#!/usr/bin/env python
#####################################################################################
#
# Copyright 2022 Quantinuum
#
# 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 htt... |
from .datastruct import *
from .exception import *
from .httpd import *
from .server import __version__
|
import uuid
from typing import Sequence, Optional, Any
from kubragen.configfile import ConfigFile
from kubragen.kdata import KData_Secret
from kubragen.kdatahelper import KDataHelper_Volume
from kubragen.option import OptionDef, OptionDefFormat
from kubragen.options import Options
class RabbitMQOptions(Options):
... |
import re
class FormatString(object):
_dependencies: list = None
_string: str = None
_name: str = None
def __init__(self, name: str, string: str, dependencies=None):
if dependencies is None:
dependencies = []
self._dependencies = dependencies
self._name = name
... |
from sqlalchemy import func
from zeus.config import db
from zeus.db.mixins import StandardAttributes
from zeus.db.utils import model_repr
from zeus.utils import timezone
class User(StandardAttributes, db.Model):
"""
Actors within Zeus.
"""
email = db.Column(db.String(128), unique=True, nullable=Fals... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
losses_model1 = [
[0.0293, 0.0212, 0.0181, 0.0156, 0.0135, 0.0120],
[0.0232, 0.0202, 0.0179, 0.0171, 0.0167, 0.0174]
]
losses_model2 = [
[0.0390, 0.0310, 0.0281, 0.0268, 0.0256, 0.0249, 0.0241, 0.0240, 0.0232, 0.0226, 0.0216, 0.0212, 0... |
from pagarme import card
from pagarme import plan
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import plan_dictionary
from tests.resources.dictionaries import transaction_d... |
#
# Represent a subset of XPath XML path syntax for use in identifying nodes in
# parse trees.
#
# <p>
# Split path into words and separators {@code /} and {@code //} via ANTLR
# itself then walk path elements from left to right. At each separator-word
# pair, find set of nodes. Next stage uses those as work list.</p>... |
"""Meta Learning Strategy"""
from keras import Model
from keras.layers import Dense
from keras.layers.merge import concatenate
from keras.utils import to_categorical
from scipy.stats import mode
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import StratifiedKFold, train_test_split
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from despike1 import despike
from ma import ma
from scipy.signal import savgol_filter
data = pd.read_excel(r'C:\Users\kaprodi\Desktop\websignal-master-Signal\Signal\pbs+.xlsx')
data_numpy = data.to_numpy().transpose()
data_y = data_numpy[1]
data_... |
"""
"""
from challenges.models import FilmChallenge
from django import forms
from django.contrib import admin
from filmlist.forms import FilmAdminForm
from filmlist.forms import SeriesAdminForm
from filmlist.models import Director
from filmlist.models import Film
from filmlist.models import Series
class FilmAdmin(adm... |
# -*- coding: utf-8 -*-
__author__ = 'Administrator'
import tornado
class BasicHandler(tornado.web.RequestHandler):
pass |
#!/usr/bin/env python
import codecs
import re
import os
from setuptools import find_packages, setup
install_requires = [
"paramiko"
]
tests_require = [
'pretend==1.0.8',
'pytest-cov==2.4.0',
'pytest==3.0.6',
# Linting
'isort==4.2.5',
'flake8==3.2.1',
'flake8-blind-except==0.1.1',
... |
import torch.nn as nn
from torch.nn.utils import weight_norm
class residual_stack(nn.Module):
def __init__(self, size, dilation):
super().__init__()
self.block = nn.Sequential(
nn.LeakyReLU(0.2),
nn.ReflectionPad1d(dilation),
weight_norm(nn.Conv1d(size, size, k... |
import Adivinhacao
import forca
def escolherJogo():
print("******************")
print("Choose youre game.")
print("******************")
escolha = int(input("1)Adivinhação\n2)Forca\nQual você quer jogar: "))
if (escolha == 1):
Adivinhacao.jogar()
elif (escolha == 2):
forca.jog... |
#!/usr/bin/env python
# from framework import *
import json
import sys
import threading
import datetime
import time
import pyschedcl as fw
import logging
import argparse
# logging.basicConfig(level=logging.DEBUG)
#os.environ['PYOPENCL_COMPILER_OUTPUT'] = '1'
def parse_arg(args=None):
parser = argparse.ArgumentPa... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Show the average of every hand written digit from the data set
def plotImage(fig, rawImg, i):
img = rawImg.reshape(28, 28)
sub = fig.add_subplot(3, 4, i + 1)
sub.set_xticks([])
sub.set_yticks([])
plt.imshow(img)
def main()... |
import tensorflow as tf
import matplotlib.pyplot as plt
"""
tf.image.crop_to_bounding_box(
image,
offset_height,
offset_width,
target_height,
target_width
)
"""
# sess = tf.Session()
#
# file_reader = tf.read_file("mifeng.png", "file_reader")
# image_decode_jpeg = tf.image.decode_jpeg(file_reader)... |
from copy import deepcopy
import torch.multiprocessing as mp
class ParameterServer(object):
def __init__(self, n_processes):
self.queue = mp.Queue()
self.lock = mp.Lock()
self.n_processes = n_processes
self.params = None
def __getstate__(self):
return (self.queue, sel... |
# project/server/main/views.py
from mayan_api_client import API
from flask import render_template, Blueprint
from flask_wtf import FlaskForm
from wtforms.fields import StringField, SelectField
from wtforms.validators import DataRequired
main_blueprint = Blueprint('main', __name__,)
api = API(host='http://192.168.... |
import torch
import dataclasses
from typing import List, Union, Optional, Tuple, Dict, Set, Any, final
from .misc import CollateData
from .tensors_data_class_base import TensorsDataClass
from .mixins import HasTargetIndexingGroupMixin, TensorDataClassWithSingleIndicesTensorMixin, \
TensorDataClassWithSingleSequenc... |
import os.path as osp
import sys
import os
import torch
import networkx as nx
import numpy as np
from torch_geometric.utils import from_networkx, to_networkx, add_self_loops
from torch.nn import Sequential,Linear,LeakyReLU,Softmax
import torch.nn.functional as F
from torch_geometric.nn import GNNExplai... |
import cv2
import numpy as np
img = cv2.imread('watch.jpeg', cv2.IMREAD_COLOR)
px = img[25, 25]
print(px)
img[250, 250] = [255, 0, 255]
watch_face = img[117:166, 352:560]
img[0:235, 0:394] = watch_face
roi = img[100:150, 100:150] = [0, 0, 0]
cv2.imshow("The images", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
import snowflake.connector
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import os
class SnowflakeConnection:
def __init__(self, **kwargs):
self.user = kwargs.get("user")
self.password = kwargs.get("password")
self.warehou... |
import smtplib
from urllib.parse import unquote
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/survey", methods=["GET"])
def echo():
mail_address = unquote(request.args.get("mail-address"))
print("ma... |
#MNIST Structure without split
#Author: Gokul Krishnan
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import tempfile
import numpy as np
import pickle
import tensorflow as tf
import utils_mnist
import sys
import se... |
# -*- coding: utf-8 -*-
import os
import platform
from fabric.api import local
from fabric.api import task
from fabric.api import lcd
from fabric.api import path
from fabric.contrib.console import confirm
from fabric_aws_lambda import SetupTask as BaseSetupTask
from fabric_aws_lambda import InvokeTask
from fabric_aws_... |
'''
Secure Triplet Loss Project Repository (https://github.com/jtrpinto/SecureTL)
File: results_analysis.py
- Reads the results pickle file saved by [trait]_test_triplet_model.py or
[trait]_test_secure_model.py and prints several performance and security
metrics, also plotting cancelability, linkability, ROC, and ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
energy = {
'BMK/cbsb7': GaussianLog('p12bmk.log'),
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('p12bmk_f12.out'),
}
frequencies = GaussianLog('p12bmkfreq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[8,10], top=[10,11... |
class DataGridRowEditEndingEventArgs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.RowEditEnding event.
DataGridRowEditEndingEventArgs(row: DataGridRow,editAction: DataGridEditAction)
"""
@staticmethod
def __new__(self,row,editAction):
""" __new__(cls: type,row: DataGridRow,... |
import unittest
import SocketServer, socket
from tests.utils import ping
from tests.mixins import ShaperMixin
import time
from shapy import register_settings
register_settings('tests.emulation.settings')
class TestCWCDelay(unittest.TestCase, ShaperMixin):
def setUp(self):
self.server_addr = ('127.0.0.2', ... |
#support ipv6
# coding=UTF-8
import struct,socket
from ctypes import *
MAX_UINT=4294967295
def ip_num2str(ip):
if ip == 0:
return "0.0.0.0"
if ip < 0:
ip = struct.unpack("I", struct.pack('i', ip))[0]
return socket.inet_ntoa(struct.pack('I',socket.htonl(ip)))
def ip_str2num... |
import pymongo
class Database(object):
def setup(self, app):
self.ip = app.config['DB_IP']
self.port = app.config['DB_PORT']
self.user = app.config['DB_USER']
self.password = app.config['DB_PASSWORD']
self.name = app.config['DB_NAME']
def connect(self):
cfg = ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 11:21:49 2020
@author: Abhishek Parashar
"""
arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
low=0
high=len(arr)-1
mid=0
while(mid<=high):
if (arr[mid]==0):
arr[low],arr[mid]=arr[mid],arr[low]
low=low+1
mid=mid+1
elif (arr[mid]... |
from conans import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake
from conan.tools.layout import cmake_layout
class LiboauthcppConan(ConanFile):
name = "liboauthcpp"
version = "0.1"
# Optional metadata
license = "MIT License"
homepage = "https://github.com/sirikata/liboauthcpp"
... |
""" Utilities to run notebooks offline, among others. CREDIT FOR MOST OF THIS GOES TO:
https://github.com/ipython/ipython/wiki/Cookbook%3a-Notebook-utilities """
import os,sys,time
from Queue import Empty
try:
from IPython.kernel import KernelManager
except ImportError:
from IPython.zmq.blockingkernelmanager... |
# THIS FILE CAN SERVE AS REFERENCE FOR FUTURE IMPLEMENTATIONS, BUT SHOULD NOT BE USED DIRECTLY
from ethereum.utils import sha3, bytes_to_int, int_to_bytes, encode_hex
import json
import random
class EphemDB():
def __init__(self, kv=None):
self.kv = kv or {}
def get(self, k):
return self.kv.ge... |
import subprocess
import sys
import yaml
def execute_command(
command,
working_directory,
environment_variables,
executor,
logger,
livestream=False
):
logger_prefix = ""
if executor:
logger_prefix = executor + ": "
process = subprocess.Popen(
... |
import locale
import re
from decimal import Decimal
from typing import Optional
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
locale.setlocale(locale.LC_MONETARY, settings.DEFAULT_LOCALE)
[THOUSAND_POINT,... |
import datetime
from django.contrib.sitemaps import Sitemap
from .models import Entry
class PulseSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
return Entry.objects.published()
def lastmod(self, obj):
return obj.pub_date
|
import os
from setuptools import setup, find_packages
VERSION = '0.0.0'
about = {
'here': os.path.abspath(os.path.dirname(__file__))
}
try:
with open(os.path.join(about['here'], 'README.md')) as f:
about['readme'] = f.read()
except IOError:
about['readme'] = 'README.md not found'
setup(
# av... |
# Script to read/plot the csv data from the energy of the modes and
import os
import glob
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
target_folder = "D:/Research/ModeTransformation/Data/05_10_2018/cropped/csv"
results_folder = os.path.join(target_folder, "png")
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# sdf_viewer_config.py
from __future__ import absolute_import, division, print_function
# this string will be used to fill the SDF file name entry field
STARTUP_SDF = ""
# used for Lipinski highlighting, change as needed
HIGHLIGHT_DICT = {"n_molwt": 500.0, "n_hbd": 5, "... |
#Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles.
#Altere o programa anterior para mostrar no final a soma dos números.
n1=int(input('Número 1: '))
n2=int(input('Número 2: '))
soma=0
while n1<n2-1:
n1+=1
print(n1)
soma+=n1
print('\n'... |
__author__ = 'spersinger'
import re
import pdb
import string
import random
import os.path
from enum import Enum
from itertools import imap
from functools import partial
from datetime import datetime, timedelta
# Field types
def load_file(name):
return [line.rstrip() for line in open(os.path.join(os.path.dirname(_... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Intel Corporation
#
# 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 os
import shutil
import sys
import unittest
from typing import List
import click
import pkg_resources
from spaceone.core import config, pygrpc, fastapi
from spaceone.core import scheduler as scheduler_v1
from spaceone.core.celery import app as celery_app
from spaceone.core.unittest.runner import RichTestRunner... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.