text
stringlengths
1
927k
# Copyright 2021 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 agreed to in writing, ...
"""Test the module .""" # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # Christos Aridas # License: MIT import pytest import numpy as np from sklearn.ensemble import GradientBoostingClassifier from imblearn.under_sampling import InstanceHardnessThreshold RND_SEED = 0 X = np.array( [ [-0...
# -*- coding: utf-8 -*- # This file is based on this gist: # http://code.activestate.com/recipes/134892/ # So real authors are DannyYoo and company. import sys if sys.platform.startswith('linux'): from .readchar_linux import readchar elif sys.platform == 'darwin': from .readchar_linux import readchar elif sys...
""" https://leetcode.com/problems/combination-sum-iii/ Tags: Practice; Concepts; Algorithms; Recursion/BackTracking; Medium """ from typing import List class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: # Create a list of nums to choose fromx return self.combi...
import numpy as np from hypernet.src.thermophysicalModels.chemistry.reactions.reactionRate import Basic class Arrhenius(Basic): # Initialization ########################################################################### def __init__( self, reactionsDatabase, *args, **kwa...
import torch from torch.autograd import Function from .util import bger, expandParam, extract_nBatch from . import solvers from .solvers.pdipm import batch as pdipm_b from .solvers.pdipm import spbatch as pdipm_spb # from .solvers.pdipm import single as pdipm_s from enum import Enum class QPSolvers(Enum): PDIPM...
# Copyright(c) 2019-2021 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # import pytest from ctypes import c_int from random import randint from pyocf.types.cache import Cache, CacheMode from pyocf.types.core import Core from pyocf.types.volume import Volume from pyocf.types.data import Data from pyo...
from django import forms class GuessForm(forms.Form): guess = forms.CharField(max_length=32)
# future from __future__ import annotations # stdlib import os from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Union # third party import ascii_magic from nacl.signing import SigningKey from nacl.signing import VerifyKey from pydantic import BaseSe...
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import TwilioTaskRouterClient # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: github.com/metaprov/modelaapi/services/modelautobuilder/v1/modelautobuilder.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from ...
from asm68.registers import * from asm68.mnemonics import TFR from asm68.asmdsl import AsmDsl, statements from asm68.assembler import assemble, InterRegisterError from helpers.code import check_object_code from pytest import raises def test_tfr_a_a(): check_object_code('1F 88', TFR, (A, A)) def test_tfr_a_b(): ...
import unittest import socket from click.testing import CliRunner from devo.common import Configuration from devo.sender.scripts.sender_cli import data from devo.sender import DevoSenderException try: from .load_certs import * except ImportError: from load_certs import * class TestSender(unittest.TestCase): ...
import numpy as np import math from pysparse.sparse import spmatrix from pysparse.itsolvers.krylov import pcg, qmrs from pysparse.precon import precon import time def poisson2d(n): L = spmatrix.ll_mat(n*n, n*n) for i in range(n): for j in range(n): k = i + n*j L[k,k] = 4 ...
# Snowflake Damage Skin success = sm.addDamageSkin(2432355) if success: sm.chat("The Snowflake Damage Skin has been added to your account's damage skin collection.")
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='royandri.dev@gmail.com', ...
def f(x): return x for i in range(1000000): f(i)
import click from typing import Dict from lmctl.client import TNCOClient, TNCOClientHttpError from lmctl.cli.arguments import common_output_format_handler from lmctl.cli.format import Table, Column from .tnco_target import TNCOTarget, LmGet, LmCreate, LmUpdate, LmDelete, LmGen class ProjectTable(Table): colum...
from direct.directnotify import DirectNotifyGlobal from direct.distributed.ClockDelta import * from direct.interval.IntervalGlobal import * from panda3d.core import * import random import FactoryEntityCreator import MintRoomBase, MintRoom import MintRoomSpecs from otp.level import DistributedLevel from otp.level impor...
from list.models import * from rest_framework import serializers class CatalogItemSerializer(serializers.ModelSerializer): class Meta: model = CatalogItem fields = ['id', 'description'] class ItemSerializer(serializers.ModelSerializer): last_checkout = serializers.SerializerMethodField() ...
"""Tests for `osxphotos exiftool` command.""" import glob import json import os import pytest from click.testing import CliRunner from osxphotos.cli.exiftool_cli import exiftool from osxphotos.cli.export import export from osxphotos.exiftool import ExifTool, get_exiftool_path from .test_cli import CLI_EXIFTOOL, PHO...
#!/usr/bin/env # -*- coding: utf-8 -*- # Copyright (C) Victor M. Mendiola Lau - All Rights Reserved # Unauthorized copying of this file, via any medium is strictly prohibited # Proprietary and confidential # Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, February 2017 import os import scipy.io as sio import...
""" Support for Homekit climate devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.homekit_controller/ """ import logging from homeassistant.components.homekit_controller import ( HomeKitEntity, KNOWN_ACCESSORIES) from homeassistant.com...
# -*- coding: utf-8 -*- import frappe from frappe.translate import rename_language def execute(): language_map = { "中国(简体)": "簡體中文", "中國(繁體)": "正體中文" } for old_name, new_name in language_map.items(): rename_language(old_name, new_name)
from moviepy.editor import VideoFileClip clip = VideoFileClip("output_images/out_video.mp4") print(clip.fps)
# -*- coding: utf-8 -*- import builtins import json import unittest import mock import pytest from django.core.exceptions import ValidationError from nose.tools import * # noqa: F403 (PEP8 asserts) from framework.auth import Auth from osf_tests.factories import (AuthUserFactory, NodeLicenseRecordFactory, ...
# -*- coding: utf-8 -*- import web from web.contrib import PyRSS2Gen import render_website as render import model import forms import logging from paginator import Paginator, PaginatorSearch, PaginatorPublicacao from datetime import datetime from configuration import WEBSITE_URL from utils import break_string urls =...
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.93 Contact: support@ory.sh Generated by: htt...
""" Common evaluation utilities. """ from collections import OrderedDict from numbers import Number import os import numpy as np def dprint(*args): # hacky, but will do for now if int(os.environ["DEBUG"]) == 1: print(args) def get_generic_path_information(paths, stat_prefix=""): """ Get an ...
#!/usr/bin/env python # encoding: utf-8 # # Copyright SAS Institute # # 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 b...
from unittest import mock from django.test import SimpleTestCase from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning from django.utils.functional import cached_property, classproperty, lazy class FunctionalTests(SimpleTestCase): def test_lazy(self): ...
# -*- coding: utf-8 -*- """ ============================ 14 - Burning ship deeper DEM ============================ Plotting of a distance estimation for the Burning ship (power-2). This zoom is deeper, featuring a miniship at 1.e-101 Reference: `fractalshades.models.Perturbation_burning_ship` """ import os import nu...
import numpy as np def calculate(list): if len(list) != 9: raise ValueError('List must contain nine numbers.') input_array = np.array([[list[0], list[1], list[2]], [list[3], list[4], list[5]], [list[6], list[7], list[8]]]) calculations = dict() print(input_array) # calc mean c_mean = n...
# -*- coding: utf-8 -*- """ wsgi module. """ from charma import CharmaApplication app = CharmaApplication() if __name__ == '__main__': app.run()
from logging import Logger from typing import cast from service.exception import ResponseException def handle_exception(e: Exception, log: Logger = Logger("Error Logger")) -> dict: log.error("Error") if isinstance(e, [ResponseException]): e: ResponseException = cast(ResponseException, e) log....
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
# Copyright 2020 The PyMC 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# 1 read file # 2 clean data # 3 tokenize # 4 eleminate stop words # 5 calculate tfidf matrix def read_file(file_path):
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # Copyright (c) 2015, Battelle Memorial Institute # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistri...
#!BPY """ Registration info for Blender menus: Name: 'AC3D (.ac)...' Blender: 243 Group: 'Export' Tip: 'Export selected meshes to AC3D (.ac) format' """ __author__ = "Willian P. Germano" __url__ = ("blender", "blenderartists.org", "AC3D's homepage, http://www.ac3d.org", "PLib 3d gaming lib, http://plib.sf.net") __ve...
# -*- coding: utf-8 -*- import datetime import logging import os from unittest import mock import pytest import elastalert.elastalert import elastalert.util from elastalert.util import dt_to_ts from elastalert.util import ts_to_dt writeback_index = 'wb' def pytest_addoption(parser): parser.addoption( "...
from django.conf import settings SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') REGISTRATION_OPEN = getattr(settings, 'REGISTRATION_OPEN', 'True')
import base64 import pytest import rlp from eth_utils import ( decode_hex, to_bytes, ValidationError, ) from eth_utils.toolz import ( assoc, assoc_in, ) from p2p.discv5.enr import ( ENR, ENRSedes, UnsignedENR, ) from p2p.discv5.identity_schemes import ( IdentityScheme, V4Iden...
from contextlib import contextmanager from enum import Enum import os import sys import tempfile from typing import Tuple, List, Generator, Optional from unittest import TestCase, main import mypy.api from mypy.modulefinder import get_site_packages_dirs from mypy.test.config import package_path from mypy.test.helpers ...
#!flask/bin/python import getopt import json import os import shutil import socket import string import random import subprocess import sys from .common.utils import try_set_file_permissions from flask import Flask, jsonify, request, abort, Response app = Flask(__name__) CLUSTER_API="cluster/api/v1.0" snapdata_path ...
# @author: GaryMK # @EMAIL: chenxingmk@gmail.com # @Date: 2021/2/14 0:28 # @Version: 1.0 # @Description: from PIL import Image, ImageDraw, ImageFont import cv2 import os def draw(pic): img = cv2.imread('source/' + pic) img = img[:, :, (2, 1, 0)] blank = Image.new("RGB", [len(img[0]), len(img)], "whit...
from nlpblock.model import *
import numpy as np import pandas as pd from pandas_datareader import data import tensorflow as tf import matplotlib.pyplot as plt import keras from keras.layers import Input, Dense, Dropout, BatchNormalization from keras.models import Model from keras.callbacks import History, CSVLogger """ Created by Mohsen Nag...
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2018年6月19日 @author: encodingl ''' import time import datetime from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler def job1(f): print(time.strftime('%Y-%m-%d %H:%M:%S', time.lo...
import datetime import peewee as pw from . import BaseModel class Server(BaseModel): id = pw.IntegerField(primary_key=True) channel = pw.IntegerField(null=False) movie_time = pw.TimeField(null=False, formats="%H:%M", default="12:00") admin_role = pw.TextField(null=False, default="Movie Master") t...
example = ''' 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 ...
#!/usr/bin/python # # 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 b...
from conans import CMake, ConanFile, tools from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.29.1" class OpenSceneGraphConanFile(ConanFile): name = "openscenegraph" description = "OpenSceneGraph is an open source high performance 3D graphics toolkit" topics = ("o...
import numpy as np from random import shuffle def svm_loss_naive(W, X, y, reg): """ Structured SVM loss function, naive implementation (with loops). Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. ...
# ------------------------------------------------ # instead of slack_bolt in requirements.txt import sys sys.path.insert(1, "vendor") # ------------------------------------------------ import logging from slack_bolt import App from slack_bolt.adapter.aws_lambda import SlackRequestHandler from slack_bolt.adapter.aws...
# -*- settings:utf-8 -*- # Flask settings import logging import os proj_name = os.environ.get('PROJECT_NAME') debug_mode = os.environ.get('FLASK_DEBUG') secret_code = os.environ.get('FLASK_SECRET') DEBUG = debug_mode TESTING = False USE_X_SENDFILE = False CSRF_ENABLED = True SECRET_KEY = secret_code # LOGGING LO...
from __future__ import absolute_import from collections import defaultdict import numpy as np import torch from torch.utils.data.sampler import Sampler class RandomIdentitySampler(Sampler): """ Randomly sample N identities, then for each identity, randomly sample K instances, therefore batch size is N*K....
import pandas import pdb from datetime import datetime import matplotlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import glob import sys from matplotlib.ticker import MultipleLocator from scipy.stats import pearsonr, spearmanr from sklearn import neighbors from sklearn....
'''define the config file for voc and resnest101os8''' import os from .base_cfg import * # modify dataset config DATASET_CFG = DATASET_CFG.copy() DATASET_CFG.update({ 'type': 'voc', 'rootdir': os.path.join(os.getcwd(), 'VOCdevkit/VOC2012'), }) DATASET_CFG['train']['set'] = 'trainaug' # modify dataloader confi...
#Solution 2 #16/3/18 Ian's Solution def ispalindrome(s): # s is the string ans = True # thats what will print out for i in range(len(s)): # loops through s which we put down in print if s[i] != s[len(s) - 1 -i]: # len s of radar is = 5 as there is 5 digits, we want to get to 0-4 so have to -1, i starts ...
""" Tic Tac Toe Reference: With modification from http://inventwithpython.com/chapter10.html. # TODOs: # 1. Find all TODO items and see whether you can improve the code. # In most cases (if not all), you can make them more readable/modular. # 2. Add/fix function's docstrings """ import random # I didn't refactor ...
#!/usr/bin/env python """ L2BD ARP term Test """ import unittest import random import copy from socket import AF_INET, AF_INET6 from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP from scapy.utils import inet_pton, inet_ntop from scapy.utils6 import in6_getnsma, in6_g...
import time from collections import deque import gym class RecordEpisodeStatistics(gym.Wrapper): def __init__(self, env, deque_size=100): super().__init__(env) self.t0 = time.perf_counter() self.episode_return = 0.0 self.episode_horizon = 0 self.return_queue = deque(maxlen...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('...
# (c) Copyright 2016 Brocade Communications Systems 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/LICEN...
from rest_framework_json_api.renderers import JSONRenderer from django.contrib.auth.models import AnonymousUser class BluebottleJSONAPIRenderer(JSONRenderer): def get_indent(self, *args, **kwargs): return 4 @classmethod def build_json_resource_obj( cls, fields, resource, ...
# Copyright 2018 Open Source Robotics Foundation, 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...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # @name : Infoga - Email Information Gathering # @url : http://github.com/m4ll0k # @author : Momo Outaadi (m4ll0k) from lib.colors import * def plus(string):print("%s[+]%s %s"%(G%0,E,string)) def warn(string):print("%s[!]%s %s"%(R%0,E,string)) def test(string):pri...
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 """ Step Functions module used throughout the ADF """ import json from time import sleep from logger import configure_logger from partition import get_partition LOGGER = configure_logger(__name__) class StepF...
import os, logging from glob import glob from pprint import pformat import yaml """ Env var expansion and merge data from: - input in yaml/json format - input file or dir of files in yaml/json format """ def merge_yaml_sources(data=None, path=None): result = {} if data: data_exp = os.path.expandvars(d...
# Copyright (c) 2014 Openstack 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 required by applicable ...
from django.urls import path from user import views app_name = "user" urlpatterns = [ path("create", views.CreateUserView.as_view(), name="create"), path("token", views.CreateTokenView.as_view(), name="token"), path("me", views.ManageUserView.as_view(), name="me"), ]
""" The media module provides a base :class:`Media` class for media objects that are tracked by Elodie. The Media class provides some base functionality used by all the media types, but isn't itself used to represent anything. Its sub-classes (:class:`~elodie.media.audio.Audio`, :class:`~elodie.media.photo.Photo`, and ...
from satlas2.core import Model, Parameter import numpy as np from scipy.special import wofz from sympy.physics.wigner import wigner_6j, wigner_3j __all__ = ['HFS'] sqrt2 = 2 ** 0.5 sqrt2log2t2 = 2 * np.sqrt(2 * np.log(2)) log2 = np.log(2) class HFS(Model): def __init__(self, I, J, A=[0, 0], B=[0, 0], C=[0, 0], ...
import calendar import math import pandas as pd import time import twstock import requests from datetime import datetime, timedelta from dateutil import relativedelta from db.Connection import session from enum import Enum from model.StockHistory import StockHistory from sys import float_info from talib import abstract...
# Arithmetic tests for DataFrame/Series/Index/Array classes that should # behave identically. # Specifically for datetime64 and datetime64tz dtypes from datetime import datetime, timedelta from itertools import product, starmap import operator import warnings import numpy as np import pytest import pytz from pandas._...
""" This module defines the database schema for resources and resource subclasses. """ from sqlalchemy import Column, Integer, String, Float from ..database import Base from spacenet.schemas.resource import ResourceType __all__ = ["Resource", "ResourceType", "ContinuousResource", "DiscreteResource"] class Resourc...
# # This code is learn Python new code, variable format string start! # Time 2020/05/15 00:44 # fatcat like ..... my_name = 'fatcat' my_age = 24 #肥猫真的24岁哦! my_height = 176 #是厘米(CM)哦! my_weight = 93 #是公斤(Kg)哦! my_eyes = 'black' my_teeth = 'white' my_hair = 'black' #上述变量被赋予了两种类型 一种是赋予变量数字值,一种是赋予变量字符串。 print(f"Let's ta...
#!/usr/bin/env python """ Illustrate the difference between corner_mask=False and corner_mask=True for masked contour plots. """ import matplotlib.pyplot as plt import numpy as np # Data to plot. x, y = np.meshgrid(np.arange(7), np.arange(10)) z = np.sin(0.5*x)*np.cos(0.52*y) # Mask various z values. mask = np.zeros_...
# Generated by Django 2.1.5 on 2019-01-30 03:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import os import random import pickle import hashlib import aiohttp from fake_useragent import UserAgent FILEPATH = os.path.dirname(os.path.abspath(__file__)) # prevent caching USER_AGENT_LIST = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0", "Mozilla/5.0 (Windows NT 10....
import sys import os import time #Import ros2 py import rclpy from rclpy.node import Node #Import messages import sensor_msgs.msg as sensor_msgs import std_msgs.msg as std_msgs #Import parameters (to read parameters) from rclpy.parameter import Parameter import numpy as np import leddar def point_cloud(points, ...
# -*- coding: utf-8 -*- """ Created on Thu Sep 9 23:21:06 2021 @author: ShiningStone """ import datetime import numpy as np from .Abstract import CWaveData,CTimeStampsGen class CDateTimeStampsGen(CTimeStampsGen): def __init__(self,start:datetime.datetime,delta:datetime.timedelta,nLen): super().__in...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from abc import ABCMeta, abstractmethod, abstractproperty from collections import Mapping import re from .channel import Channel, MultiChannel from .dist import Dist from .index_record import IndexRecord from .v...
# Copyright 2018 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.txt" file accom...
""" Django settings for blog project. Generated by 'django-admin startproject' using Django 2.2. 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 os # Buil...
# -*- coding: UTF-8 -*- # Copyright 2017-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """The choicelists for this plugin. """ from lino.api import dd, _ class PartnerTariffs(dd.ChoiceList): verbose_name = _("Client tariff") verbose_name_plural = _("Client tariffs") add = PartnerTariff...
from synapse.syncmd import exec_cmd from synapse.synapse_exceptions import ResourceException from synapse.logger import logger log = logger('yum-pkg') def install(name): ret = exec_cmd("/usr/bin/yum -q -y install {0}".format(name)) if ret['returncode'] != 0: raise ResourceException(ret['stderr']) d...
# -*- coding: utf-8 -*- # (c) Copyright 2020 Sensirion AG, Switzerland from __future__ import absolute_import, division, print_function import logging log = logging.getLogger(__name__) class SensorBridgeI2cError(IOError): """ I2C transceive error. """ def __init__(self, code, message="Unknown"): ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import unittest import yaml from maro.data_lib.ecr.vessel_parser import VesselsParser from maro.data_lib.ecr.entities import VesselSetting conf_str = """ vessels: rt1_vessel_001: capacity: 92400 parking: duration: 1 noise...
import abc import logging import traceback from django.conf import settings from corehq.pillows.mappings.utils import transform_for_es7 from corehq.util.es.elasticsearch import bulk, scan class AbstractElasticsearchInterface(metaclass=abc.ABCMeta): def __init__(self, es): self.es = es def get_alias...
from brave.overlays.overlay import Overlay from gi.repository import Gst class EffectOverlay(Overlay): ''' For doing applying a video effect. ''' def permitted_props(self): return { **super().permitted_props(), 'effect_name': { 'type': 'str', ...
# -*- coding: UTF-8 -*- import os import sys if sys.version_info.major == 2: # python2 import ConfigParser as configparser else: # python3 import configparser from .plugin import PyTestRailPlugin from .testrail_api import APIClient def pytest_addoption(parser): group = parser.getgroup('testrail')...
# TestSwiftPOSysTypes.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONT...
import itertools import numpy as np from brian2.parsing.bast import brian_dtype_from_dtype from brian2.parsing.rendering import NumpyNodeRenderer from brian2.core.functions import DEFAULT_FUNCTIONS, timestep from brian2.core.variables import ArrayVariable from brian2.utils.stringtools import get_identifiers, word_sub...
__all__ = ["GenericWildcardPrincipalRule", "PartialWildcardPrincipalRule", "FullWildcardPrincipalRule"] import logging import re from typing import Dict, Optional from pycfmodel.model.cf_model import CFModel from pycfmodel.model.resources.iam_managed_policy import IAMManagedPolicy from pycfmodel.model.resources.iam_po...
""" An implementation of Karger's Algorithm for partitioning a graph. """ from __future__ import annotations import random # Adjacency list representation of this graph: # https://en.wikipedia.org/wiki/File:Single_run_of_Karger%E2%80%99s_Mincut_algorithm.svg TEST_GRAPH = { "1": ["2", "3", "4", "5"], "2": ["1...
""" Assembly """ import os from setuptools import setup, find_packages base_dir = os.path.dirname(__file__) __about__ = {} with open(os.path.join(base_dir, "assembly", "about.py")) as f: exec(f.read(), __about__) with open('requirements.txt') as f: install_requires = f.read().splitlines() with open("READM...
import csv import requests df = open("bridgeData3.csv",'r').readlines() fin = open('final.csv','r').readlines() finCsv = fin[1:] # url = https://b2ptc.herokuapp.com/bridges finalCsv = df[1:] obj = {} for i in finalCsv: x = i.split(',') obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_img':x[2],'after_im...