content stringlengths 5 1.05M |
|---|
import os
import shutil
from subprocess import call
import pytest
# this is deprecated, sould be @pytest.fixture
# but travis uses an old version of pytest for python 3.4
@pytest.yield_fixture(scope="class")
def test_directory_fixture():
base_dir = os.getcwd()
test_dir_name = 'temp_directory1'
full_p... |
# @lc app=leetcode id=710 lang=python3
#
# [710] Random Pick with Blacklist
#
# https://leetcode.com/problems/random-pick-with-blacklist/description/
#
# algorithms
# Hard (33.27%)
# Likes: 497
# Dislikes: 83
# Total Accepted: 22.2K
# Total Submissions: 66.8K
# Testcase Example: '["Solution","pick","pick","pick"... |
"""Front end for Quack"""
from lark import Lark, Transformer
import argparse
import sys
from typing import List, Tuple
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def cli():
cli_parser = argparse.ArgumentParser()
cli_parser.add_argument("source", type=ar... |
from flask import make_response, request, render_template, redirect, url_for
from models.session import Session
from models.user import User
from werkzeug.security import check_password_hash
class LoginView:
RESULT_INVALIDCREDENTIALS = "invalidcredentials"
def __init__(self):
self.session = Session(r... |
# -*- coding: utf-8 -*-
import random as rand
from library.welcomeScreen import welcome
from library.farwell import showTotalScoreBye
# https://stackoverflow.com/questions/20309456/call-a-function-from-another-file
name, questionsNum = welcome()
questionsKeeper = 1
rightAns = 0
progress = ''
while ques... |
from sortingandsearching.count_values_in_range import *
class TestCountValuesInRange:
def test_arrays_of_length_2_or_less(self):
assert count([1], lower=1, upper=2) == 1
assert count([1], lower=2, upper=2) == 0
assert count([2, 1], lower=1, upper=2) == 2
assert count([3, 1]... |
# -*- coding: utf-8 -*-
#
"""
Partie arithmetique du module lycee.
"""
def pgcd(a, b):
"""Renvoie le Plus Grand Diviseur Communs des entiers ``a`` et ``b``.
Arguments:
a (int) : un nombre entier
b (int) : un nombre entier
"""
if a < 0 or b < 0:
return pgcd(abs(a), abs(b))
... |
# -*- coding:utf-8 -*-
from apus.users.models import Users
from apus.config.db import save_in_db, query
def create_user():
print("Criar novo usuário")
username = input('username: ')
email = input('email: ')
user = Users(username=username, email=email)
save_in_db(user)
def list_users():
prin... |
import json
import boto3
import dynamo_handler
import yelp_handler
import sqs_handler
import sns_handler
def lambda_handler(event, context):
#api_key= Hidden Due to security reasons
#queue_url = Hidden Due to security reasons
slot_list,message_list = sqs_handler.message_handle(queue_url)
if slot_list... |
import gc
import io
import os
import piexif
import pytest
from PIL import Image, ImageCms
import pillow_heif
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
def to_pillow_image(heif_file):
return Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
... |
from chass.locate_commands import locate_commands
import subprocess
def sedcommand (thepassedfile, commands, params):
f = open(thepassedfile,"r+")
g = open("copy2.sh","w+")
sed_count=0
lines = f.readlines()
sed_ls = []
for a,b in commands:
if(b=="sed"):
sed_ls.append(a)
for index in sed_ls:
lines[index]... |
import math
from rlbot.agents.base_agent import SimpleControllerState
from action.base_action import BaseAction
from mechanic.drive_navigate_boost import DriveNavigateBoost
class Kickoff(BaseAction):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mechanic = DriveNavig... |
import logging
import os
from pathlib2 import Path
from os import makedirs, path
class LoggingFileHandler(logging.FileHandler):
def __init__(self, dir_name, fileName, mode):
if not Path(dir_name).exists():
makedirs(dir_name)
file_path = path.join(dir_name, str(os.getpid()) + "_" + f... |
import media
import fresh_tomatoes
# Create instances of class `Movie` - for each movie.
the_terminator = media.Movie("The Terminator",
"1 hour 48 minutes",
"The story of a cyborg sent past in time.",
"Sci-fi, Action",
... |
import time
from concurrent.futures import (
CancelledError,
ProcessPoolExecutor,
ThreadPoolExecutor,
)
import pytest
from bbhnet.parallelize import AsyncExecutor, as_completed
def func(x):
return x**2
def func_with_args(x, i):
return x**i
def sleepy_func(t):
time.sl... |
from ._ybins import YBins
from ._xbins import XBins
from ._stream import Stream
from ._marker import Marker
from ._line import Line
from ._hoverlabel import Hoverlabel
from plotly.graph_objs.histogram2dcontour import hoverlabel
from ._contours import Contours
from plotly.graph_objs.histogram2dcontour import contours
fr... |
"""Functions"""
import os
import sys
from sys import exit, stderr, argv, path, modules
from os.path import isfile, isdir, realpath, dirname, exists
import numpy as np
import pandas as pd
# plotting
import matplotlib
import seaborn.apionly as sns
from matplotlib import rc
import matplotlib.lines as mlines
import pylab a... |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021
#
# 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
# r... |
import sys,os,subprocess,logging
from engine import MatchingEngine
className = "BundlerMatching"
class BundlerMatching(MatchingEngine):
featuresListFileName = "list_features.txt"
executable = ''
def __init__(self, distrDir):
if sys.platform == "win32":
self.executable =... |
"""
Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
"""
import sys
# программа умышленно сделана настойчива на ответ.
def ask_repeat(msg=""):
res: bool = False
if len(msg):
... |
import torch.nn as nn
import torchquantum as tq
import torchquantum.functional as tqf
import numpy as np
from typing import Iterable
from torchquantum.plugins.qiskit_macros import QISKIT_INCOMPATIBLE_FUNC_NAMES
from torchpack.utils.logging import logger
class QuantumModuleFromOps(tq.QuantumModule):
def __init_... |
"""miIO protocol implementation
This module contains the implementation of the routines to encrypt and decrypt
miIO payloads with a device-specific token.
The payloads to be encrypted (to be passed to a device) are expected to be
JSON objects, the same applies for decryption where they are converted
automatically to ... |
#!/usr/bin/env python
# encoding: utf-8
import setuptools #import setup
from numpy.distutils.core import setup, Extension
import os
import platform
os.environ['NPY_DISTUTILS_APPEND_FLAGS'] = '1'
# Source order is important for dependencies
f90src = ['WavDynMods.f90',
'PatclVelct.f90',
'BodyIntgr.... |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from kabzimal.rest.views.category import CategoryViewSet
from kabzimal.rest.views.category_type import CategoryTypeViewSet
from kabzimal.rest.views.invoices import InvoicesViewSet
from kabzimal.rest.views.orders import OrdersView... |
import time
from anubis.lms.autograde import bulk_autograde
from anubis.models import db
from anubis.utils.data import with_context
from anubis.utils.testing.db import clear_database
from anubis.utils.testing.seed import create_assignment, create_course, create_students, init_submissions
def do_seed() -> str:
cl... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CategoriesConfig(AppConfig):
name = 'joorab.apps.categories'
verbose_name = _("Categories")
def ready(self):
from . import signals
|
#coding:utf-8
from pyglet.gl import *
import OpenGL.GL.shaders
import ctypes
import pyrr
import time
from math import sin
class Triangle:
def __init__(self):
self.triangle = [-0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
0.0, 0.5, 0.0... |
from sys import prefix
import boto3
import botocore.exceptions
from core.utils import get_path
class Storage:
def __init__(self, bucket_name: str, index: str = 'index.html') -> None:
self.__client = boto3.resource('s3')
self.__bucket_name = bucket_name
self.__index = index
def get_i... |
def extractMatchashortcakeWordpressCom(item):
'''
Parser for 'matchashortcake.wordpress.com'
'''
return None |
# coding: utf-8
# In[ ]:
import pandas
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_extraction import DictVectorizer
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
import glob
import datetime
import itertools
from time import sleep
# In[ ]:
np.random.seed(1)
#... |
import copy
import random
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.keychain import BaseProjectKeychain
from cumulusci.core.config import OrgConfig
def random_sha():
hash = random.getrandbits(128)
return "%032x" % hash
def cre... |
from dataclasses import dataclass
from .t_participant_association import TParticipantAssociation
__NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL"
@dataclass
class ParticipantAssociation(TParticipantAssociation):
class Meta:
name = "participantAssociation"
namespace = "http://www.omg.... |
"""
Copyright (c) 2012-2013 Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met: * Redistributions of source code must retain the above cop... |
import fileinput
counter = 0
triangles = []
templines = []
for line in fileinput.input():
templines.append([int(a) for a in line.split()])
if len(templines) == 3:
for asdf in range(3):
triangles.append((templines[0][asdf], templines[1][asdf], templines[2][asdf]))
templines = []
fo... |
import time
from nitter_scraper import NitterScraper
last_tweet_id = None
with NitterScraper(port=8008) as nitter:
while True:
for tweet in nitter.get_tweets("dgnsrekt", pages=1, break_on_tweet_id=last_tweet_id):
if tweet.is_pinned is True:
continue
if tweet.is_r... |
from torch import cat, cos, float64, sin, stack, tensor
from torch.nn import Module, Parameter
from core.dynamics import RoboticDynamics
class CartPole(RoboticDynamics, Module):
def __init__(self, m_c, m_p, l, g=9.81):
RoboticDynamics.__init__(self, 2, 1)
Module.__init__(self)
self.params... |
import sys
import ast
import inspect
import textwrap
from typing_inspect_isle import class_typevar_mapping
from dataclasses import (
is_dataclass,
MISSING as DC_MISSING,
asdict,
fields as dc_fields,
Field as DCField,
)
from typing import (
Any,
Type,
Dict,
cast,
Union,
Mappin... |
"""Unit and functional tests."""
|
#!/usr/bin/env python3
"""tests for max_rep.py"""
from subprocess import getstatusoutput, getoutput
import os
import random
import re
import string
import max_rep
prg = "./max_rep.py"
# --------------------------------------------------
def test_usage():
"""usage"""
rv1, out1 = getstatusoutput(prg)
asser... |
import autoencoder as ae
import numpy as np
import itertools
import pandas as pd
import os
import sys
from sklearn.model_selection import train_test_split
def main(*argv):
# Starting dimensions
dims = 190
# K-fold folds
folds = 5
# Grid search params
lr = [0.0001, 0.001, 0.01, 0.1]
batch =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
def concat_classes(classes):
"""
Merges a list of classes and return concatenated string
"""
return ' '.join(_class for _class in classes if _class)
|
#-------------------------------------------------------------
# Name: Create Portal Content
# Purpose: Creates a list of portal content from a CSV file. Can set to only create a single
# item type from the CSV or everything in the CSV.
# - Create... |
import pygame
from src.menu import Menu, Button
from src.screen import Screen
from src.game import Game
def runGame(screen, tutorialMenu, fakeNewsMenu):
game = Game(screen, tutorialMenu, fakeNewsMenu)
game.run(screen)
pygame.init()
screen = Screen((1920, 1080), "Stop the count!", fullScreen=False)
tutorialM... |
import tkinter
import tkinter.filedialog
import tkinter.ttk
from . import screens
class Interface(tkinter.Tk):
def __init__(self, control):
super(Interface, self).__init__()
self._control = control
self._create_widgets()
self._create_commands()
self._create_styles()
... |
"""
`minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers.
This module contains helper functions for the minion-ci server and client
:copyright: (c) by Timo Furrer
:license: MIT, see LICENSE for details
"""
import os
from urllib.parse import urlparse
def get_... |
import time
from collections import deque
from threading import Lock, Condition, Thread
from senders.gbn_sender import GoBackNSender
from senders.udt_sender import UDTSender, LossyUDTSender, CorruptingUDTSender
from helpers.logger_utils import get_stdout_logger
from receivers.udt_receiver import UDTReceiver, Interrup... |
from dataclasses import dataclass
from typing import Optional, List
@dataclass(frozen=True)
class Country:
country_code: Optional[str]
country_id: Optional[int]
is_licensed: Optional[bool]
name: Optional[str]
@dataclass(frozen=True)
class Countries:
countries: List[Country]
|
import random
import logging
import pandas as pd
import numpy as np
import altair as alt
from sklearn.preprocessing import LabelBinarizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model... |
from tkinter import *
from tkinter import ttk
from tkinter.font import Font
ventana=Tk()
notebook=ttk.Notebook(ventana)
notebook.pack(fill="both", expand="yes", )
pes0=ttk.Frame(notebook)
pes1=ttk.Frame(notebook)
pes2=ttk.Frame(notebook)
pes3=ttk.Frame(notebook)
pes4=ttk.Frame(notebook)
notebook.add(pes0, text="RESTAU... |
from .schema import *
from .api import *
from . import examples
from ...datasets import (
list_datasets,
load_dataset
)
from ... import expr
from ...expr import datum
from .display import VegaLite, renderers
from .data import (
pipe, curry, limit_rows,
sample, to_json, to_csv, to_values,
defaul... |
from ckeditor.widgets import CKEditorWidget
from django import forms
from django.contrib import admin
from .models import Picture, Album, Video
# Register your models here.
class InlinePicture(admin.TabularInline):
model = Picture
class AlbumAdmin(admin.ModelAdmin):
inlines = [InlinePicture]
class Video... |
# pylint: disable=import-error
# pylint: disable=no-member
from copy import deepcopy
import numpy as np
import time
import torch
import abc
from termcolor import cprint
from gym.spaces import Box
import torch.nn as nn
import pickle as pkl
import scipy
import flare.kindling as fk
from flare.kindling import ReplayBuffer
... |
from ftfy.fixes import (
fix_encoding, fix_encoding_and_explain, apply_plan, possible_encoding,
remove_control_chars, fix_surrogates
)
from ftfy.badness import sequence_weirdness
import unicodedata
import sys
# Most single-character strings which have been misencoded should be restored.
def test_bmp_character... |
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
# GP means
class decaying_exponential(nn.Module):
def __init__(self, dims, a, b, learnable=[True, True]):
"""
:param int neurons: the number of output dimensios
:param float a: initial value for all :math:`a` tens... |
import json
from jupyter_server.base.handlers import APIHandler
from jupyter_server.utils import url_path_join
import tornado
import pkg_resources
import os
import io
import zipfile
import pooch
_wasm_filenames = {
"wdirect.wasm": (
"https://unpkg.com/emulators@0.0.55/dist/wdirect.wasm",
"11bff62... |
import tempfile
import pandas as pd
from joblib import dump
import numpy as np
from sklearn.linear_model import ElasticNet
from sklearn.metrics import make_scorer, mean_squared_error
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from analysis.hit_ratio_error import hit_ratio_error
from utils.loggi... |
from traceback_with_variables import prints_tb, ColorSchemes
@prints_tb(
num_context_lines=3,
max_value_str_len=100,
max_exc_str_len=1000,
ellipsis_='...',
color_scheme=ColorSchemes.synthwave,
)
def f(n):
print(1 / n)
def main():
f(0)
main()
|
# coding: utf-8
"""
Statuspage API
# Code of Conduct Please don't abuse the API, and please report all feature requests and issues to https://help.statuspage.io/help/contact-us-30 # Rate Limiting Each API token is limited to 1 request / second as measured on a 60 second rolling window. To get this limit incr... |
#
# plot-trav-wave-x
# Plot spatial profile of a travelling wave
#
# Sparisoma Viridi | https://butiran.github.io
#
# 20210206
# 0525 Learn to plot from [1].
# 0538 Learn from [2].
# 0544 Use \pi from [3].
# 0557 Can draw a sine function.
# 0604 Learn add_subplot [4].
# 0618 Just know this one [5].
# 0639 Read styl... |
import main
async def create(bot):
with open('../web/db.sqlite3', 'rb') as database_file:
await main.send_file_to_global_admin(database_file, bot)
|
# partially based on https://github.com/hiram64/temporal-ensembling-semi-supervised
import sys
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.losses import mean_squared_error
from lib.utils import to_onehot
def create_loss_func(num_class, class_distr, ssl_method=None, to_retur... |
import json
from flask import Flask, send_from_directory, render_template, request
import get_data
app = Flask(__name__)
@app.route("/")
def index():
start = request.cookies.get("start") or "000.jpg"
grid = ""
bounds = ""
figures = ""
if start[0] == "1":
grid = " checked"
if start[1]... |
"""Converts DC2G data to TFRecords file format with Example protos."""
import os
import sys
import tensorflow as tf
import matplotlib.pyplot as plt
import csv
from dc2g.util import get_training_testing_houses, get_object_goal_names
dir_path, _ = os.path.split(os.path.dirname(os.path.realpath(__file__)))
# dataset =... |
import struct, re
import pyretic.vendor
from ryu.lib.packet import *
from ryu.lib import addrconv
from pyretic.core import util
from pyretic.core.network import IPAddr, EthAddr
__all__ = ['of_field', 'of_fields', 'get_packet_processor', 'Packet']
_field_list = dict()
IPV4 = 0x0800
IPV6 = 0x86dd
VLAN = 0x8100... |
import re
from collections import Counter
from collections import defaultdict
import numpy as np
def read_voc_pos_tags_from_conllu_file(filename):
file = open(filename, 'r', encoding="utf8")
pos_tags = []
vocabulary = []
sentences = []
text = file.read()
for sentence in text.spli... |
#!/usr/bin/env pytest -vs
"""Tests for awssh."""
# Standard Python Libraries
import logging
import os
import sys
from unittest.mock import patch
# Third-Party Libraries
import pytest
# cisagov Libraries
from awssh import awssh
log_levels = (
"debug",
"info",
"warning",
"error",
"critical",
)
# ... |
import torch
from torch import nn
from transformers import AutoModel, AutoTokenizer
from datasets import load_dataset
from datasets import Value
from torch.utils.data import DataLoader
from torch import optim
from poutyne import Model, Lambda
from poutyne_transformers import TransformerCollator, ModelWrapper
print("Lo... |
import numpy as np
import sys
from datetime import datetime
from datetime import timedelta
import matplotlib.pyplot as plt
from tools_TC202010 import read_nc, prep_proj_multi_cartopy, setup_grids_cartopy, draw_rec_4p, get_besttrack, read_obs_letkf
import cartopy.crs as ccrs
import cartopy.feature as cfeature
quick ... |
# explore also shapely.strtree.STRtree
from geosqlite import Writer, Reader
from shapely.wkb import loads as wkb_loads
from shapely.wkt import loads as wkt_loads
from shapely.geometry import shape, asShape, mapping
import pythongis as pg
from time import time
def timings():
print 'loading'
data = pg.Vecto... |
#!/usr/bin/env python3
from gene_disease import restClient, geneClient, getGeneList
import multiprocessing as mp
from nested_dict import nested_dict
import sqlite3
from sqlite3 import Error
import collections
import dill
def create_connection(db_file):
""" create a database connection to the SQLite database
... |
import random
command = '''
welcome to world of game!
Even me(sidhant) developer doesnot know the
correct guess ,its generated randomly.
best luck!
'''
print(command)
op = ""
num = ''
number = random.randint(40,50)
out = {
number:'👌👏',
'1':'one',
'2':'two',
'3':'three',
'4':'f... |
# Copyright 2018 The Bazel 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 la... |
from unittest import mock
from github3.orgs import ShortOrganization, ShortTeam
from github3.repos import ShortRepository
from github3.users import ShortUser
from git_sentry.handlers.git_org import GitOrg
from git_sentry.handlers.git_repo import GitRepo
from git_sentry.handlers.git_team import GitTeam
from git_sentry... |
import magma as m
def verilog_name(name):
if isinstance(name, m.ref.DefnRef):
return str(name)
if isinstance(name, m.ref.ArrayRef):
array_name = verilog_name(name.array.name)
return f"{array_name}_{name.index}"
if isinstance(name, m.ref.TupleRef):
tuple_name = verilog_name(... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
ISO request molecule design pool set association table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
fr... |
u"""Cheshire3 ResultSetStore Unittests.
A ResultSet is collection of results, commonly pointers to Record typically
created in response to a search on a Database.
A ResultSetStore is a persistent storage mechanism for ResultSet objects.
ResultSetStore configurations may be customized by the user. For the purposes
of... |
from django.apps import AppConfig
class WarriorsConfig(AppConfig):
name = 'warriors'
|
#!/usr/bin/evn python3
"""
This script loads a pretrained NN model and .
Created by: Vice, 16.10.2021
"""
import torch
import torch.nn as nn
import numpy as np
import gc
from NN_dataset import test_loader
import math
from NN_params import *
# Append the required sys.path for accessing utilities and save the data direc... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
def color_to_grayscale(color_array: np.ndarray) -> np.ndarray:
return cv2.cvtColor(color_array, cv2.COLOR_BGR2GRAY)
def calcPSD(input_image, output_image, flag):
# Complex input image with zero imaginary component
X = np.fft.rfft2(input_ima... |
import actions
from loader import Loader
LOADER = Loader()
def lambda_handler(event, context):
try:
LOADER.forecast_cli.delete_dataset_import_job(
DatasetImportJobArn=event['DatasetImportJobArn']
)
actions.take_action_delete(
LOADER.forecast_cli.describe_dataset_im... |
from typing import List
import pandas as pd
from sqlalchemy import Integer
from sqlalchemy.sql.schema import Column
from datapipe.datatable import DataStore, DataTable
from datapipe.compute import Pipeline, Catalog, Table, DatatableTransform
from datapipe.core_steps import BatchGenerate
from datapipe.run_config impo... |
__version__ = "0.1.1"
from .core import find, MarkerNotFound
|
#!/usr/bin/env python
import os
import uuid
import logging
from ConfigParser import ConfigParser
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.error import NoRouteError
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import Applicatio... |
def notas(*args, situacao=False):
"""
=> Recebe várias notas de um aluno e retorna:
- A quantidade de notas recebidas
- A maior nota
- A menor nota
- A média da turma
- A situação académica (opcional)
:param notas: recebe várias notas
:param situacao: (opcional) mostra ou não a situação académica
:return: dic... |
from helpers.kafka_helpers import create_consumer, poll_for_valid_message
from helpers.f142_logdata import LogData, Value, Double
from helpers.flatbuffer_helpers import check_message_pv_name_and_value_type
from time import sleep
def test_forwarder_sends_fake_pv_updates(docker_compose_fake_epics):
# A fake PV is d... |
from django.apps import AppConfig
class SampleappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'backend.sampleapp'
|
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import subprocess
from .platform_determiner_base import platform_determiner_base
from .linux_os_release import linux_os_release
from .linux_lsb_release import linux_lsb_release
class platform_determiner_linux(platform_determin... |
import click
import sys
from . import analysisPipeline
@click.group()
def main(args=None):
pass
@main.command()
@click.argument('inputdir', type=click.Path(exists=True))
@click.argument('phenodata', type=str)
def modelStep1(inputdir, phenodata=None):
"""
Run accordJP pipeline, starting launch model s... |
# pylint: disable=missing-docstring
import unittest
from pathlib import Path
from handsdown.processors.pep257 import PEP257DocstringProcessor
class TestLoader(unittest.TestCase):
def test_init(self):
pep257_docstring = (
Path(__file__).parent.parent / "static" / "pep257_docstring.txt"
... |
import os
from typing import Callable
from unittest import TestCase
from tempfile import mkstemp
from ygo_core.deck import Deck
class TestDeck(TestCase):
def setUp(self) -> None:
self.deck = Deck()
def base_test_load(self, content: str, assertfunc: Callable[[], None]) -> None:
fd, name = m... |
class LeaderShape(Enum, IComparable, IFormattable, IConvertible):
"""
Supported geometric shapes of annotation leaders.
enum LeaderShape,values: Arc (2),Kinked (1),Straight (0)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
... |
"""pytorchfi.error_models provides different error models out-of-the-box for use."""
import logging
import torch
from pytorchfi import core
from pytorchfi.util import *
# Helper functions
def random_value(min_val=-1, max_val=1):
return random.uniform(min_val, max_val)
def random_weight_location(pfi, layer=-1):
... |
l = [10, 20, 30, 40, 50]
print(l[:2], l[2:])
print(l[::2])
s = slice(None, None, 2)
print(l[s])
l = list(range(10))
print(l)
print(l[2:5])
l[2:5] = [20, 30]
print(l)
print([1, 2] * 5)
board = [['_'] * 3 for i in range(3)]
print(board)
board[1][2] = 'X'
print(board)
weird_board = [['_'] * 3] * 3
print(weird_board... |
# Date: 28 Aug 2021
# Mini Python - For Beginners Exercise by #TechwithTim known as Tim Ruscica
# Youtube link: https://www.youtube.com/watch?v=DLn3jOsNRVE&t=1933s
# Exercice: Rock, Paper, Scissors
# My Exercise Objectives
# No.1 write out the code outlined by #TechwithTim exercise
# No.2 to flag identify what... |
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stk=[]
for i in num:
while k and stk and stk[-1]>i:
stk.pop()
k-=1
stk.append(i)
return ''.join(stk[:-k or None]).lstrip("0") or "0"
|
from typing import Any
from ..protocol import Observable, Observer, Subscription, rx_observer_from
from .rx_create import rx_create
from .rx_reduce import rx_reduce
__all__ = ["rx_avg"]
def rx_avg(observable: Observable) -> Observable:
"""Create an observable wich return the average items in the source when com... |
# $Id: 411_fmtp_amrnb_offer_band_eff.py 3664 2011-07-19 03:42:28Z nanang $
import inc_sip as sip
import inc_sdp as sdp
# Answer for codec AMR should not contain fmtp octet-align=1
sdp = \
"""
v=0
o=- 3428650655 3428650655 IN IP4 192.168.1.9
s=pjmedia
c=IN IP4 192.168.1.9
t=0 0
a=X-nat:0
m=audio 4000 RTP/AVP 99 101
a=... |
from stix_shifter_modules.splunk.entry_point import EntryPoint
from unittest.mock import patch
import unittest
import json
import os
from stix_shifter.stix_transmission import stix_transmission
from stix_shifter_utils.utils.error_response import ErrorCode
class SplunkMockResponse:
def __init__(self, response_code,... |
# pylint: disable = redefined-outer-name
from typing import Union
import py
import pytest
from universum import __main__
from .conftest import FuzzyCallChecker
from .git_utils import GitServer, GitClient, GitTestEnvironment
from .perforce_utils import PerforceWorkspace, P4TestEnvironment
from .utils import LocalTestE... |
from __future__ import absolute_import
# EAI fields
from builtins import object
EAI_ACL = 'eai:acl'
EAI_ATTRIBUTES = 'eai:attributes'
EAI_USER = 'eai:userName'
EAI_APP = 'eai:appName'
EAI_FIELD_PREFIX = 'eai:'
EAI_FIELDS = [EAI_ACL, EAI_ATTRIBUTES, EAI_USER, EAI_APP]
# elements of eai:attributes
EAI_ATTRIBUTES_OPTI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.