content
stringlengths
0
894k
type
stringclasses
2 values
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, GMapOptions from bokeh.plotting import gmap output_file("gmap.html") map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11) # For GMaps to function, Google requires you obtain and enable an API key: # # h...
python
""" Common utility functions for NPP/SNPP """ import os import numpy as np from pathlib import Path # Country enumerations EN = "en" WA = "wa" SC = "sc" NI = "ni" # Aggregations EW = [EN, WA] GB = [EN, WA, SC] UK = [EN, WA, SC, NI] # ONS country codes CODES = { EN: "E92000001", WA: "W92000004", SC: "S92...
python
from __future__ import print_function from utensor_cgen.ir import uTensorGraph from utensor_cgen.ir.utils import graph_check from utensor_cgen.transformer import CMSIS_NN_Transformer def test_cmsisnn_trnasformer(fusion_graph_tuple): (ugraph, ugraph1) = fusion_graph_tuple transformer = CMSIS_NN_Transformer() ...
python
import requests import json import execjs # 必须,需要先用pip 安装,用来执行js脚本 from urllib.parse import quote # 用来判断是否需要打印日志 debug = True class Py4Js: def __init__(self): self.ctx = execjs.compile(""" function TL(a) { var k = ""; var b = 406644; var b1 ...
python
import torch import torch.nn as nn import torch.optim as optim import numpy as np import matplotlib.pylab as plt import random from celluloid import Camera class Energy(nn.Module): def __init__(self): super(Energy, self).__init__() self.sigma = nn.Parameter(torch.tensor([0.5])) self.mu = nn.Parameter(torch.tens...
python
import scrapy from celery import Celery from scrapy.settings import Settings from scrapy.spiders import Spider from scrapyscript import Job, Processor, ScrapyScriptException from spiders import ItemSpider, TitleSpider app = Celery("hello", broker="amqp://guest@localhost//") @app.task def celery_job(url): job = ...
python
from copy import copy from Cat.utils.collections_ import ChainedList from model.commands.argumentTypes import * from model.commands.command import CommandSchema, KeywordSchema, ArgumentSchema, TERMINAL, COMMANDS_ROOT, SwitchSchema from model.data.mcVersions import MCVersion def fillCommandsFor1_17(version: MCVersion...
python
# -*- coding: utf-8 -*- # Port of the official ttgo library for the LilyGo TTGO T-Watch 2020. # Author: Nikita Selin (Anodev)[https://github.com/OPHoperHPO] import gc import _thread import axp202 import lvgl as lv import st7789_lvgl import ft6x36 from bma42x import BMA42X from pcf8563 import PCF8563 from machine import...
python
# https://leetcode.com/problems/longest-common-prefix/ class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return '' # since list of string will be sorted and retrieved min max by alphebetic order s1, s2 = min(strs), max(strs) for i, c in...
python
from django.apps import AppConfig class S3FileConfig(AppConfig): name = 'apps.s3file'
python
""" test_django-oci api ------------------- Tests for `django-oci` api. """ from django.urls import reverse from django.contrib.auth.models import User from django_oci import settings from rest_framework import status from rest_framework.test import APITestCase from django.test.utils import override_settings from tim...
python
from _todefrost import package_md5sum md5 = None try: with open('/flash/package.md5') as f: md5 = f.read().strip() except Exception as e: pass if md5 != package_md5sum.md5sum: print("package md5 changed....defrosting...") from _todefrost import microwave microwave.defrost() import mach...
python
#!/usr/bin/env python import pytest from clichain import cli, pipeline import click from click.testing import CliRunner import sys import ast import logging from difflib import SequenceMatcher def test_main_help(): tasks = cli.Tasks() args = ['--help'] result = cli.test(tasks, args) print('>> test_ma...
python
compiler = 'C:\\Users\\Public\\Documents\\Mikroelektronika\\mikroC PRO for PIC\\mikroCPIC1618.exe' settings = { 'cmdln0': '"{compiler}" -MSF -DBG -p{device} -GC -DL -O11111110 -fo{clock} -N"{project}" "{filename}"', 'cmdlnSP': '-SP"{path}"', 'cmdlnIP': '-IP"{path}"', 'cmdlnLIBS': '"__Lib_Math.mcl" "__L...
python
from rest_framework import serializers from .models import Post, Category class BlogCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'name', 'created_at', 'updated_at', ] class BlogPostSerializer(serializers.Mode...
python
from dictpy.dict_search import DictSearch from dictpy.serializer import Serializer __all__ = ["DictSearch", "Serializer"]
python
import pandas as pd class TrainDataSampler: def name(self): raise NotImplementedError def sample(self, df): raise NotImplementedError class CompleteData(TrainDataSampler): def name(self): return 'complete_data' def sample(self, df): return df class BalancedExampl...
python
from unbillit_project import app if __name__ == '__main__': app.run(host='127.0.0.1', port=8000, debug=True) ############## set envirnment variable for secret key ############# # Add password strength validators later to user/form.py # work on putting everything together # implement password reset functiona...
python
import psycopg2 import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from numpy import random from sklearn.preprocessing import StandardScaler import os os.chdir('/home/rafalb/work/molecules/chemicalSmilesSpace/src') from keras.layers import LSTM, TimeDistributed, concatenate, Input, ...
python
from django.db import models class Contact(models.Model): first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) email = models.CharField(null=False, blank=False, max_length=50) ip = models.CharField(null=False, blank=...
python
""" Provides animated GIF images of weather-radar imagery derived the Australian Bureau of Meteorology (http://www.bom.gov.au/australia/radar/). """ import datetime as dt import io import logging import os import re import time import PIL.Image import requests # Legend: # # NSW: http://www.bom.gov.au/australia/radar...
python
from AttachmentFetcherGUI import runGUI runGUI()
python
from typing import Tuple import numpy as np import tensorflow as tf from absl import logging from xain.datasets import prep from xain.types import KerasHistory, KerasWeights, Metrics, VolumeByClass from . import ModelProvider class Participant: # pylint: disable-msg=too-many-arguments # pylint: disable=too...
python
#!/usr/bin/env python3 import sys import heapq # Generates gawk code. Run this manually and update hinter.awk if you don't like current alphabet or want to increase number of hints. # # This script builds prefix code for given number of hints using n-aray Huffman Coding. # We precompute hints for hinter.awk to make it...
python
#!/usr/bin/python2.7 # -*- coding=utf-8 -*- ################################################################## # WaterLevelTree Test # Goal: Test script for WaterLevelTree algorithm # Author: wenchieh # # Project: eaglemine # waterleveltree.py # Version: # Date: November 29 2017 # Main Contact...
python
from restaurant import Restaurant rest1 = Restaurant('Alitas y Costillas', 'BBQ') print(rest1.describe_restaurant()) print(rest1.open_restaurant()) from user import Admin admin1 = Admin('Antonio', 'Perez', '25', 'Monterrey, Nuevo Leon') admin1.privileges = ['Edit', 'Delete', 'Ban'] print(admin1.describe_User()) admin...
python
#!/usr/bin/env python3 """ See freq_response.md for details """ from dataclasses import dataclass import fractions import math from typing import Iterable, Optional, Tuple, Union import numpy as np from analysis import linearity, time_domain_response from utils import utils from unit_test import unit_test from pro...
python
""" 2019/12/23 23:42 162.【正则表达式】开始结束和或语法 """ import re # TODO: 1. ^托字号: 表示以...开始 """ 如果是在中括号中,那么代表取反操作. """ text1 = 'hello' ret_text1 = re.match('^h', text1) print('^托字号: 表示以...开始...') print(ret_text1.group()) # TODO: 2.$ 表示以...结束 email = 'hynever@163.com' ret_email = re.match('\w+@163\.com$', email) print('$ 表示以.....
python
import paddle import paddle.nn.functional as F import random import numpy as np import math from PIL import Image from ..registry import PIPELINES from collections.abc import Sequence import cv2 import random @PIPELINES.register() class Toskeleton(object): """ transpose (M,T,V,2) to (2,T,V,...
python
class RoundEdge: def __init__(self, r, obj): self.r = r self.obj = obj self.material = obj.material self.color = obj.color def signedDistance(self, point): return self.obj.signedDistance(point) - self.r def evalColorAtPoint(self, point): return self.obj.ev...
python
# -*- coding: utf-8 -*- """ unistorage.adapters.amazon ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module an adapter for Amazon Simple Storage Service (S3). :copyright: (c) 2012 by Janne Vanhala. :license: BSD, see LICENSE for more details. """ from datetime import datetime, timedelta from email.utils import...
python
import numpy as np import time #Note, all modes should have a return to forward, to prevent stucks def forward_mode(Rover): # Calm the roll and pitch if (Rover.roll >= 1.5 and Rover.roll <= 358.5) or (Rover.pitch >= 1.5 and Rover.pitch <= 359): Rover.max_vel = 0.5 else: Rover.max_vel = 5 ...
python
# License: MIT License import typing import numpy as np class Trajectory(object): """ Abstracts the infos about a complete set of trajectories, represented as a numpy array of doubles (the time deltas) and a numpy matrix of ints (the changes of states). :param list_of_columns: the list containing the...
python
# -*- coding: utf-8 -*- # Copyright 2016 Battelle Energy Alliance, 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 ...
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Conversions between formats.""" import numpy as np import pytest from .. import linear as _l from ..io import LinearTransformArray as LTA @pytest.mark.parametrize( "filename", [ "f...
python
import sys import os class Configuration: ###################################### ###### Configuration parameters ###### ###################################### # Change them if required # path to the root of ExaHyPe from this file pathToExaHyPERoot = os.path.abspath(os.path.join(os.pa...
python
from socket import socket, AF_INET, SOCK_STREAM from message_handler import MessageHandler from string_match import match from rsa_ops import init_rsa class Client: def __init__(self, server_adr, bsize=1024): self.server_adr = server_adr # a tuple self.bsize = bsize self.pubkey, self.priv...
python
from django.db import models from datetime import date class CompletionDate(models.Model): """Store a task completion on a certain date""" completion_date = models.DateField(auto_now_add=True, primary_key=True) class Task(models.Model): """Daily task model and related functions""" task_id = models.A...
python
#!/usr/bin/env python import keras import numpy as np from imgaug import augmenters as iaa from keras.applications.mobilenet import preprocess_input from keras.preprocessing.image import image class CustomDataGenerator(keras.utils.Sequence): """ Takes input of image paths and corresponding labels and generat...
python
# Generated by Django 3.2.7 on 2021-10-06 22:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0008_alter_review_reviewer'), ] operations = [ migrations.AlterField( model_name='watchl...
python
# # PySNMP MIB module APPACCELERATION-STATUS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-STATUS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import os import sys if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess from . import common as cmn task_registry = {} def task(task_func): ""...
python
#!/usr/bin/env python """Test for near equality """ import unittest class AlmostEqualTest(unittest.TestCase): def testNotAlmostEqual(self): self.failIfAlmostEqual(1.1, 3.3 - 2.0, places=1) def testAlmostEqual(self): self.failUnlessAlmostEqual(1.1, 3.3 - 2.0, places=0) if __name__ == '__m...
python
import pytest from generalizer import generalize_label test_data = [ ('enter the email associated with your account', 'email'), ('zip code', 'ZIPcode'), ('postal code', 'ZIPcode'), ('first name', 'firstname'), ('last name', 'surname'), ('city', 'city'), ('reference name', 'name'), ('pas...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import sys from json import loads as json_loads from wolframclient.utils import six from wolframclient.utils.encoding import force_text # Python 3.4 and 3.5 json loads only accept str. if sys.version_info[0] == 3 and sy...
python
from csc148_queue import Queue class Tree: """ A bare-bones Tree ADT that identifies the root with the entire tree. """ def __init__(self, value=None, children=None): """ Create Tree self with content value and 0 or more children @param Tree self: this tree @param obj...
python
pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24] def mean(dataset): return sum(dataset) / len(dataset) print(mean(pythonic_machine_ages)) print(sum(pythonic_machine_ages))
python
""" business days module """ from datetime import timedelta, date from collections.abc import Generator import holidays def business_days_list(sdate: date, edate: date) -> list[date]: """ get business days for start and end date inclusive """ days = [] us_holidays = holidays.UnitedStates() for num ...
python
from random import randint from math import hypot, fabs, ceil class AudioSource: def __init__(self, pos, tile): self.pos = pos self.tile = tile def ValidatedMove(self, velocity, map): new_location = {'tile' : [self.tile.pos[0], self.tile.pos[1]], 'position' : [0, 0]} if...
python
* * * * * * * * * * * * * * * * * * PRINT TRIANGLE LOOK LIKE THIS =========================================== for row in range(7): for col in range(7): if(row-col==row)or(row==6)or(row==col): print("*",end=" ") else: ...
python
DEPARTMENTS_MAP = { "che": "Chemical", "che-idd": "Chemical IDD", "cer": "Ceramic", "cer-idd": "Ceramic IDD", "civ": "Civil", "civ-idd": "Civil IDD", "cse": "Computer Science", "cse-idd": "Computer Science IDD", "eee": "Electrical", "eee-idd": "Electrical IDD", "ece": "Electr...
python
# -*- coding: utf-8 -*- __author__ = 'study_sun' from spider_base.downloader import * import sys reload(sys) sys.setdefaultencoding('utf-8') class IndexDownloader(SBDownloader): pass
python
INPUT_IMAGE_WIDTH = 1024
python
##### Imports ##### from datetime import date, datetime import json import dateutil.parser import babel from flask import ( Flask, render_template, request, Response, flash, redirect, url_for) from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_migrate ...
python
#!/usr/bin/env python """ a collection of functions for reading EEG signals and applying basic filtering operations """ import os import scipy.io import numpy as np from scipy.signal import butter, lfilter def butter_lowpass(cutoff, fs, order=5): """ wrapper for calculating parameters of a lowpass filter ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.db import models, migrations import orchestra.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_...
python
raise ValueError("test failed! wrapper did not ignore polluted PWD. either the wrapper is faulty, or ooni is still unpatched (Tor bug #13581)")
python
"""empty message Revision ID: 879fe8a73df4 Revises: 8c3766231a8f Create Date: 2018-06-07 19:56:40.800424 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '879fe8a73df4' down_revision = '8c3766231a8f' branch_labels = None depends_on = None def upgrade(): # ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('peacecorps', '0035_auto_20141202_2354'), ] operations = [ migrations.AddField( model_name='campaign', ...
python
import time from flask import request, jsonify, make_response from app import app from controllers.mock_data import request_method_list, get_mock_data @app.route('/mock/<path:path>', methods=request_method_list) def mock_call(path): try: if not path.startswith('/'): path = "/" + path ...
python
# Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See L...
python
"""Routines for performing spectral unmixing on earth engine images.""" import ee as _ee from tqdm import tqdm as _tqdm from .utils import selectSpectra as _selectSpectra # this function must be run before any of the specific unmixing routines are set def Initialize(sensor, n=30, bands=None): """Initializes sen...
python
from builtins import * import numpy as np import scipy.linalg from scipy.special import gammaln, digamma from bnpy.suffstats import ParamBag, SuffStatBag from bnpy.util import LOGTWO, LOGPI, LOGTWOPI, EPS from bnpy.util import dotATA, dotATB, dotABT from bnpy.util import as1D, as2D, as3D, toCArray from bnpy.util impor...
python
import networkx as nx import operator import matplotlib.pyplot as plt g = nx.read_weighted_edgelist('data/edgelist24.csv') degree = nx.degree(g) numNodes = nx.number_of_nodes(g) numEdges = nx.number_of_edges(g) minDegree = min([item[1] for item in degree]) maxDegree = max([item[1] for item in degree]) print(degree) ...
python
# Copyright 2019 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, ...
python
import vcr from .common import * from keepassxc_pwned.cli import main_wrapper from keepassxc_pwned.parser import Database db_file_loc = os.path.join(db_files, "duplicate_entry.kdbx") db_pw = "duplicate_entry" @pytest.fixture() def database(): db: Database = Database(pathlib.Path(db_file_loc)) db._password ...
python
import sys import logging import random import numpy as np import os # from nltk.corpus import wordnet as wn import argparse import torch import pickle from transformers import GPT2Tokenizer, TransfoXLTokenizer from shutil import copyfile import collections from multiprocessing.pool import Pool import multiprocessing ...
python
from keras.models import load_model import cv2 import numpy as np from mtcnn.mtcnn import MTCNN cap = cv2.VideoCapture(0) model = load_model('../model/face-detector-model.h5') size = (200, 200) detector = MTCNN() while True: ret, frame = cap.read() faces = detector.detect_faces(frame) for face in fac...
python
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
python
from mayan.apps.testing.tests.base import BaseTestCase from ..events import event_otp_disabled, event_otp_enabled from .mixins import AuthenticationOTPTestMixin class UserOTPDataTestCase(AuthenticationOTPTestMixin, BaseTestCase): create_test_case_superuser = True def test_method_get_absolute_url(self): ...
python
import xlwings as xw import requests from aruba import Config, switch def vlans(data): """Enumera las VLANs del switch""" # Obtengo el workbook, las coordenadas y la dirección IP del servidor API wb, row, col, api_host = splitExcel(data) # Y ahora, obtengo los datos del switch with switch.sessio...
python
""" module(requirement) - Python依赖. Main members: # check_requirement - 检查依赖. """ from qytPython import logger # 模块与pypi对应关系 module_pypi_config = { 'docx': 'python-docx', 'yaml': 'PyYAML' } def check_requirement(module_obj, module_name): """ 检查依赖. @params: ...
python
import numpy as np # See discussion around this question: https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve/2022348#2022348 def index_of_elbow(points): """Returns the index of the "elbow" in ``points``. Decently fast and pretty approximate. Performs worse with disproporti...
python
from .abstract import * from .. import schema class Lead( ListableAPIResource, MutableAPIResource ): """ Attributes: assessment_run_id (str): ID of the associated assessment run confidence (mage.schema.Confidence): Confidence level of the lead created_at (str): When the lead was created...
python
# Generated by Django 3.1.4 on 2021-01-02 07:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', ...
python
import unittest import numpy as np from svreg.summation import Rho, FFG from tests._testStructs import _all_test_structs, r0 class Test_Summation(unittest.TestCase): def setUp(self): self.ffg = FFG( name='ffg', allElements=['H', 'He'], neighborElements=['H', 'He'], ...
python
from .testing import Tester from .training import Trainer from .dataloader import multiview_dataloader def get_trainer(cfg, net, optimizer, device=None): return Trainer(cfg=cfg, net=net, optimizer=optimizer, device=device) def get_tester(cfg, net, device=None): return Tester(cfg=cfg, net=net, device=device) ...
python
from datetime import timedelta, datetime from django.conf import settings from django.utils.timezone import make_aware import pytz from rest_framework import exceptions from rest_framework.authentication import TokenAuthentication import logging logger = logging.getLogger(__name__) class BearerAuthentication(TokenA...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ hdf5events.py Description: """ # Package Header # from ..__header__ import * # Header # __author__ = __author__ __credits__ = __credits__ __maintainer__ = __maintainer__ __email__ = __email__ # Imports # # Standard Libraries # import datetime import time import uuid ...
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Module Level Imports # ----------------------------------------------------------------------------- from .typings import ( missing, snowflake, nullable, string, optional, snowflakearray, ...
python
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt class Logger: def __init__(self, cnf): self.dat, self.acc, self.cnf = [], 0, cnf self.path_out = cnf.path_out self.path_out += '/{0}/'.format(self.cnf.log_name) self.pa...
python
import speech_recognition as sr import subprocess from subprocess import call import os import gnk import time os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "//add_credentials" def prepare_date(self): self.response = self.response + self.result[2:18] def prepare_time(self): self.response = self.response + se...
python
'''Checkout how many servers I'm used in!''' import discord from discord.ext import commands from packages.utils import Embed, ImproperType import textwrap import lorem import math from mongoclient import DBClient client = discord.Client class Command(commands.Cog): def __init__(self, client): self.clien...
python
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script generates header/source files with C++ language bindings # for the X11 protocol and its extensions. The protocol information # is obtained fro...
python
from math import sin, radians #for i in range(100): # r = radians(i) # # print(f" sinus z {i} = {sin(i)}") # print(f" sinus z {r} = {sin(r)}") x = 0 i = 0 while x < 1: i = i + 1 r = radians(i) x = sin(r) print(i,r,x) x = 0 i = 0 while True: i = i + 1 r = radians(i) x = sin(r) i...
python
# Generated by Django 2.2.13 on 2020-06-18 21:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('oidc_provider', '0027_token_refresh_token_expire_at'), ] operations = [ migrations.AddField( model_name='client', n...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayBossRelatedCompanyConsultModel(object): def __init__(self): self._biz_time_in_mills = None self._is_whole_month_valid = None self._type = None self._value = ...
python
from .cprint import aprint, printInfo from .utils import Utils
python
#!/usr/bin/env python # Copyright 2018 Criteo # # 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 agree...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
python
''' Script to check the correctness of the clustering. ''' import unittest import os import numpy as np from pixel_clusterizer.clusterizer import HitClusterizer, default_hits_dtype, default_clusters_dtype, default_clusters_descr, default_cluster_hits_dtype def create_hits(n_hits, max_column, max_row, max_frame, ma...
python
# -*- coding: utf-8 -*- # Copyright CERN since 2022 # # 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 ...
python
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from tests.test_files import html_doc def mocked_requests_get(*args, **kwargs): """this method will be used by the mock to replace requests.get""" class MockResponse: def __init__(self, html, status_code): sel...
python
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories class GoogleComputeIPForward(BaseResourceCheck): def __init__(self): name = "Ensure that IP forwarding is not enabled on Instances" id = "CKV_GCP...
python
import pytest from leapp.exceptions import InvalidTagDefinitionError from leapp.tags import Tag, get_tags, ExperimentalTag, DisabledTag class TestTag(Tag): name = "test-tag" def test_tag_members_correctly_set(): assert hasattr(TestTag, 'Common') and TestTag.Common.name == 'common-test-tag' assert hasat...
python
from django.contrib import admin from .models import name_cat,items_cat from django.db import models from mdeditor.widgets import MDEditorWidget # Register your models here. @admin.register(name_cat) class Name_admin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',)} @admin.register(items_cat) class Ite...
python
import json import os from solc import compile_standard from web3.contract import ConciseContract from web3 import Web3, HTTPProvider OUTPUT_DIR = os.environ['HOME'] + '/plasma-dex/plasma/root_chain/build/contracts' class Deployer(object): def __init__(self, eth_node_endpoint): provider = HTTPProvider(et...
python
# Unit test for bayesnet_inf_autodiff import numpy as onp # original numpy import jax.numpy as np from jax import grad import bayesnet_inf_autodiff as bn # Example from fig 3 of Darwiche'03 paper # Note that we assume 0=False, 1=True so we order the entries differently thetaA = np.array([0.5, 0.5]) # thetaA[a] = P(A...
python
#! /usr/bin/env python #IDN #This node subscribes to the topics which include motor RPM speeds published by arduino analog outputs def wheels2twist(w1,w2,w3,w4): l_x = 0.33 r = 0.0762*2 l_y = 0.33 d=1/(l_x+l_y) I_J = np.array([[ 1, 1, 1, 1 ], [ 1, -1, -1, ...
python
import serial import config from time import sleep config.x = 0 config.y = 0 config.PORT = '/dev/ttyACM0' ser = None def setup(): global ser ser = serial.Serial(config.PORT, 9600, timeout=1) st = serial_read() print(st) def serial_write(s): t = s global ser if ser is None: return "Er...
python