content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import re
import requests
from datetime import datetime
try:
import constants as const
except ImportError:
import ogame.constants as const
class OGame(object):
def __init__(self, universe, username, password, user_agent=None, proxy='', language=None):
self.universe = universe
self.usernam... | python |
"""
Unit tests for the Deis example-[language] projects.
Run these tests with "python -m unittest client.tests.test_examples"
or with "./manage.py test client.ExamplesTest".
"""
from __future__ import unicode_literals
from unittest import TestCase
from uuid import uuid4
import pexpect
import time
from .utils import... | python |
# -*- coding: utf-8 -*-
"""
@author: vladimirnesterov
Ten Little Algorithms by Jason Sachs from here https://www.embeddedrelated.com/showarticle/760.php
"""
def euclidean_gcd(a,b):
"""Euclidean Algorithm to find greatest common divisor.
Euclidean algorithm is an efficient method for computing
the gre... | python |
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
# a = 5
# for i in range(a):
# i+=1
# for j in range(1):
# print(str(i)," ", str(j))
'''
Задача 2
Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5.
'''
# a = i... | python |
#!/usr/bin/env python3
import os
import re
from datetime import datetime, timedelta, timezone
import dateutil.parser
from tempfile import mkstemp
import shutil
from urllib.parse import urlparse, parse_qs
import itertools
import functools
import requests
import hoordu
from hoordu.models import *
from hoordu.plugins i... | python |
# GetAppStats
#
import requests
import os
import datetime, time
import mysql.connector as mysql
from biokbase.catalog.Client import Catalog
from biokbase.narrative_method_store.client import NarrativeMethodStore
requests.packages.urllib3.disable_warnings()
catalog = Catalog(url=os.environ["CATALOG_URL"], token=os.en... | python |
# problem - https://practice.geeksforgeeks.org/problems/longest-common-substring1452/1
class Solution:
def longestCommonSubstr(self, S1, S2, n, m):
res = 0
rows,col = n+1,m+1
dp = [[0]*col for i in range(rows)]
for i in range(1,rows):
for j in range(1,col):
... | python |
from requests import Response
import cattr
from fixtures.register.models import RegisterUserResponse
from common.deco import logging as log
class Register:
def __init__(self, app):
self.app = app
POST_REGISTER = '/register'
@log('Register new user')
def register(self, data, type_response=R... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# File: ./setup.py
# Author: Jiří Kučera <sanczes AT gmail.com>
# Date: 2021-06-21 23:58:43 +0200
# Project: vutils-testing: Auxiliary library for writing tests
#
# SPDX-License-Identifier: MIT
#
"""Setup for vutil... | python |
#!/usr/bin/env python3
"""GALI BAI
Script to generate a list of genome track view plot for user defined gene list.
Prints out a png files.
"""
import os
import sys
from collections import defaultdict
from optparse import OptionParser
import pandas as pd
import subprocess
def main():
usage = "USAGE: %prog -i [track... | python |
from os.path import exists
from typing import Any, Literal, Optional
from aiofiles import open
from aiofiles.os import mkdir
from aiohttp.client import ClientSession
from rabbitark.config import Config
from rabbitark.utils.default_class import DownloadInfo
from rabbitark.utils.request import SessionPoolRequest
clas... | python |
import unittest
import os
import numpy
from worldengine.draw import _biome_colors, draw_simple_elevation, elevation_color, \
draw_elevation, draw_riversmap, draw_ocean, draw_precipitation, \
draw_world, draw_temperature_levels, draw_biome, draw_scatter_plot, draw_satellite
from worldengine.biome import Biome
f... | python |
# coding: utf-8
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import os
app = dash.Dash(__name__)
server = app.server
# read data for tables (one df per table)
df_fund_facts = pd.read_c... | python |
#
# PySNMP MIB module JUNIPER-SIP-COMMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-SIP-COMMON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:01:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | python |
from typing import Generic, TypeVar, Type, Optional, List
from pydantic import BaseModel
from pymongo.database import Database
from bson import ObjectId
SchemaType = TypeVar("SchemaType", bound=BaseModel)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bo... | python |
# -*- coding: utf-8 -*-
a = 5
if a == 5:
print("Has acertado en el número")
else:
print("NO has acertado en el numero")
| python |
import urllib
from flask import session, url_for
from . import BasePlugin
class User(object):
"""
User model
AuthenticationBackend plugins should return an instance of this from their authenticate() metdods
"""
def __init__(self, username, name, groups=None, user_data=None):
self.usernam... | python |
import argparse
import json
import os
from pycocotools import mask
import numpy as np
from PIL import Image, ImageFont, ImageDraw
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', dest='file', default='coco_annotations.json', help='coco annotation json file')
parser.add_argument('-i', '--image_i... | python |
from jumpscale import j
from .NodeNas import NodeNas
from .NodeHost import NodeHost
from .NodeMonitor import NodeMonitor
from .MonitorTools import *
from .InfluxDumper import *
import os
JSBASE = j.application.jsbase_get_class()
class PerfTestToolsFactory(JSBASE):
"""
j.tools.perftesttools.getNodeMonitor("... | python |
import sys
input = sys.stdin.readline
# input
t = int(input())
opt = [[0 for _ in range(10)] for _ in range(1001)]
i = 1
opt[1] = [1 for _ in range(10)]
for _ in range(t):
n = int(input())
# process
'''
opt(i, j)를 길이가 i이면서 j로 끝나는 비빌번호의 수라 하자.
opt(i, 0) = opt(i-1, 7)
opt(i, 1) = opt(i-1, 2) + opt(i-1, 4)
opt(i, 2)... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
.. module:: position
:platform: Unix
:synopsis: the top-level submodule of T_System's remote_ui that contains the functions for managing of t_system's arm.
.. moduleauthor:: Cem Baybars GÜÇLÜ <cem.baybars@gmail.com>
"""
from tinydb import Query # TinyDB is a li... | python |
from typing import List
def two_sum(lis: List[int], target: int):
dici = {}
for i, value in enumerate(lis):
objetive = target - value
if objetive in dici:
return [dici[objetive], i]
dici[value] = i
return []
print(two_sum([1, 2, 3, 4, 5, 6], 7))
| python |
import bcrypt
import jwt
from bookqlub_api import utils
from bookqlub_api.schema import models
from tests import base_test
class TestUserSchema(base_test.BaseTestSchema):
mutation = """
mutation CreateUser($full_name: String!, $username: String!, $pass: String!) {
createUser(fullName: $full... | python |
import random
import time
import eppy.doc
from past.builtins import xrange # Python 2 backwards compatibility
from .util import randid
class Behavior(object):
def __init__(self, ctx, logger=None):
self.ctx = ctx
self.logger = logger or self.ctx.getLogger(self)
def __call__(self, client):
... | python |
# coding: utf-8
# In[1]:
"""
Deep Deterministic Policy Gradient (DDPG), Reinforcement Learning.
1-way relay, net bit rate, energy harvesting example for training.
Thanks to : https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/tree/master/contents/9_Deep_Deterministic_Policy_Gradient_DDPG
Using:
te... | python |
# coding: utf-8
import os
import re
import requests
# Check the link is directory or not
def is_dir(url):
if "tree" in url:
return "tree"
elif "blob" in url:
return "blob"
else:
return "root"
def get_blob(url, save_location):
None
def get_tree(url, save_location):
None
... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 7 14:04:20 2018
@author: pgallego
"""
import numpy as np
from keras.callbacks import TensorBoard,ModelCheckpoint
from vgg16 import CreateModel
from PrepareDate import PrepareData
import os
input_shape=226
channels=3
X_train,y_train,X_val,y_val,X_test,y_test = Prep... | python |
# device provisioning - automate devices configuration files
def greeting(name):
print("Hello", name)
greeting(input("What is your name: \n"))
if_name = input("Please provide the interface name: \n")
if_name = if_name.lower()
print(if_name)
# ip_addr = '10.1.10.254'
# vrf = 'lab'
# ping = 'ping {} vrf {} '.... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""XML to dict parse."""
import json
import textwrap
from configparser import ConfigParser
from pathlib import Path
from typing import Iterable
import untangle
from jira_freeplane.common import LOG
from jira_freeplane.mm_settings import MMConfig
class Node:
"""Node... | python |
from spidermon.contrib.actions.telegram.notifiers import (
SendTelegramMessageSpiderFinished,
)
from spidermon.contrib.scrapy.monitors import ErrorCountMonitor, FinishReasonMonitor
from spidermon.core.suites import MonitorSuite
class SpiderCloseMonitorSuite(MonitorSuite):
monitors = [
ErrorCountMonito... | python |
arr = [1, 4, 7, 9, 14, 17, 39, 56]
targets = (8, 39)
def linear_search(arr, target):
"""
>>> all(linear_search(arr, x) == arr.index(x) if x in arr else -1 for x in targets)
True
"""
for i, item in enumerate(arr):
if item == target:
return i
return -1
for ta... | python |
"""Test subscriptions interact with ISAs:
- Create an ISA.
- Create a subscription, response should include the pre-existing ISA.
- Modify the ISA, response should include the subscription.
- Delete the ISA, response should include the subscription.
- Delete the subscription.
"""
import datetime
from monit... | python |
import argparse
import glob
import os
import pandas as pd
import numpy as np
import cv2
from math import sqrt
import random
import wget
import zipfile
'''
Labels used in
[1] T. Kawashima et al., "Action recognition from extremely low-resolution
thermal image sequence," 2017 14th IEEE International Conference on ... | python |
class Account:
"""
Class that generates new instances of accounts
"""
account_list = []
def __init__(self,account_name,password):
"""
__init__ method that helps us define the properties for our objects
Args:
account_name: New account name
... | python |
"""
Problem 16: https://projecteuler.net/problem=16
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
def solution(power: int = 1000) -> int:
"""
Returns the sum of the digits of the number 2^power.
>>> solution(1000)
1366
... | python |
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
@app.route('/parse/json', methods=['GET', 'POST', 'DELETE', 'PUT'])
def add():
if request.headers.get("Content-Type") == 'application/json':
# HTTPリクエストのMIMEタイプがapplication/json
data = request.get_json()
return... | python |
import logging
from subprocess import (
PIPE,
Popen
)
SUDO_PATH = '/usr/bin/sudo'
SUDO_PRESERVE_ENVIRONMENT_ARG = '-E'
SUDO_USER_ARG = '-u'
log = logging.getLogger(__name__)
def sudo_popen(*args, **kwargs):
"""
Helper method for building and executing Popen command. This is potentially
sensetive... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_visualise_graph.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog_visualiseGraph(object):
def setupUi(self, Dialog_v... | python |
#!/usr/bin/env python
# Copyright (c) 2005 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# o Redistributions of source code must retain the above copyright notic... | python |
from voluptuous import *
from ..defaults import settings, filtertypes
from ..exceptions import ConfigurationError
from . import SchemaCheck
import logging
logger = logging.getLogger(__name__)
def filtertype():
return {
Required('filtertype'): Any(
In(settings.all_filtertypes()),
msg... | python |
sessions = int(input())
teams = [int(x) for x in input().split()]
possible = True
for i in range(sessions - 1):
if teams[i] < 0: possible = False
teams[i+1] -= teams[i]%2
if teams[sessions - 1] % 2 == 1: possible = False
print("YES" if possible else "NO") | python |
# Copyright (c) 2014, Yuta Okamoto <okapies@gmail.com>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .validators import boolean, integer, mutually_exclusive
class Source(AWSProperty):
props = {
'Password': (str, False),
'Revision': (... | python |
# posting to: http://localhost:3000/api/articles/update/:articleid with title, content
# changes title, content
#
# id1: (darwinbot1 P@ssw0rd!! 57d748bc67d0eaf026dff431) <-- this will change with differing mongo instances
import time # for testing, this is not good
import requests # if not installed already, run python... | python |
import re
from src.util import poe_consts
from src.util.logging import log
from src.util.pob import pob_conf
class Gem:
__slots__ = 'name', 'level', 'quality', 'id', 'skill_part', 'enabled', 'second_name', 'active_part', 'is_active'
def __init__(self, id, name, level, quality, skill_part, enabled=''):
... | python |
#! /usr/bin/python
#Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDI... | python |
import unittest
from unittest.mock import Mock
from data_repo_client import RepositoryApi
from dagster_utils.contrib.data_repo.jobs import poll_job, JobFailureException, JobTimeoutException
from dagster_utils.contrib.data_repo.typing import JobId
class PollJobTestCase(unittest.TestCase):
def setUp(self):
... | python |
from gobbli.dataset.cmu_movie_summary import MovieSummaryDataset
from gobbli.dataset.imdb import IMDBDataset
from gobbli.dataset.newsgroups import NewsgroupsDataset
from gobbli.dataset.trivial import TrivialDataset
__all__ = ["TrivialDataset", "NewsgroupsDataset", "IMDBDataset", "MovieSummaryDataset"]
| python |
from argparse import ArgumentParser
from datetime import datetime
time_now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.Ar... | python |
"""changed covid to remove source
Revision ID: faaf679b71ce
Revises: d57323c5f17d
Create Date: 2020-03-23 14:18:04.931393
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'faaf679b71ce'
down_revision = 'd57323c5f17d'
branch_labels = None
depends_on = None
def ... | python |
from abc import ABC
import scrapy
import re
import json
from copyheaders import headers_raw_to_dict
from ..items import HistoricNetValueItem
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
'''... | python |
from Optimizador.C3D import *
t = -1
e = -1
def getEncabezado():
content = "from goto import with_goto\n"
content += "from Instrucciones.TablaSimbolos.Tabla import Tabla\n"
content += "from Instrucciones.Sql_insert import insertTable\n"
content += "from Instrucciones.Sql_drop import DropTable,DropData... | python |
from django.contrib import admin
from . import models
admin.site.register(models.Training)
admin.site.register(models.Education)
admin.site.register(models.Experience)
admin.site.register(models.Skills)
admin.site.register(models.cv) | python |
from builtins import license
from os.path import basename
from typing import List
from pydantic import BaseModel
from iiif_binder import Config, Metadata, Image
def generate_manifest(
identifier: str, config: Config, metadata: Metadata, images: List[Image]
) -> dict:
manifest = {
"@context": "http:/... | python |
from PyQt5 import QtCore
from pyqtgraph import PlotCurveItem, PlotDataItem, ImageItem
from .DataItem import ExtendedDataItem
from ...logging import get_logger
logger = get_logger("PlotMenu")
class PlotMenuMixin:
def raiseContextMenu(self, ev):
"""
Raise the context menu, removing extra separators ... | python |
# Copyright (c) 2019, Piet Hein Schouten. All rights reserved.
# Licensed under the terms of the MIT license.
from .card import Card
from .file_attachment import FileAttachment
from .retrieval_attempt import RetrievalAttempt
from .tag import Tag
| python |
"""Module for the custom Django sampledata command."""
import csv
import random
from django.core import management
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.gis.geos import Point
from allauth.account.models import EmailAddress
from tests.users.factories import ... | python |
# https://leetcode.com/problems/search-a-2d-matrix/
#
# Write an efficient algorithm that searches for a value in an m x n matrix.
# This matrix has the following properties:
#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the previous row.
#
#... | python |
from django.shortcuts import render, redirect
from comments.forms import CommentForm
from django.http import HttpResponseBadRequest
# Create your views here.
def create_comment(request):
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = requ... | python |
#!/usr/bin/python3 -OO
# Copyright 2007-2020 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... | python |
from gatekeeper import Endpoint
class Hello(Endpoint):
path = '/hello'
def get(self, request, response):
response.body = 'hello world'
| python |
from app import manager
if __name__ == "__main__":
manager.run()
| python |
from __future__ import annotations
from src.models.verse_reference import VerseReference
class ChapterReference:
book_name: str
chapter_number: int
version: str
def __init__(self, book_name: str, chapter_number: int, version: str) -> None:
self.book_name = book_name
self.chapter_numb... | python |
# Copyright 2017 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... | python |
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | | | \ analysis
___/... | python |
#!/usr/bin/env python3
# Get one postal code from the command line
# Example ./get_latlong_cmd A1B2C3
import sys
import os
import googlemaps
import json
gmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])
code = sys.argv[1]
print(code)
place_result = gmaps.find_place(input = code,
... | python |
import coreapi
import coreschema
from django_filters.rest_framework import DjangoFilterBackend
from drf_haystack.filters import HaystackFilter
from drf_haystack.generics import HaystackGenericAPIView
from rest_framework import viewsets
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions imp... | python |
from django.urls import path, include
from rest_framework import routers
from . import viewsets
router = routers.SimpleRouter()
router.register('namespaces', viewsets.NamespaceViewSet)
app_name = 'api'
urlpatterns = [
path('', include(router.urls)),
]
| python |
import logging
import numpy as np
from Bio import SeqIO
logger = logging.getLogger(__name__)
import os
import re
import sys
import click
import pandas as pd
import typing as t
sys.path.append("..")
from utils.rna_struct_utils import RNAStructUtils
df = pd.DataFrame({"id": [1, 2, 3, 4]})
def get_secondary_struct(... | python |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=0)
config.add_route('home', '/')
config.add_route('auth', '/auth')
config.add_route('pantry', '/pantry')
config.add_route('detail', '/detail/{upc}')
config.add_route('manage_item', '/manage_item')
config.add_rout... | python |
from method import *
from friends import *
import numpy as np
import os
import sys
# Run FOF algorithm on all blocks of data in 'split_dir'
'''
Required parameters in config file:
directory, split_dir, m1, m2, t_gap, v_gap, tstart, tsamp, vsamp, fof_testing_mode
And from FITS header:
TBIN, CHAN_BW, OBSF... | python |
class ClientTrader():
def __init__(self) -> None:
pass
def login(self) -> None:
pass
if __name__ == '__main__':
pass
| python |
#
# Copyright 2021 Budapest Quantum Computing Group
#
# 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 |
selenium_wrapper_web_driver_not_found_error = "Web Driver not found"
selenium_wrapper_opera_path_error = "Opera need executable path"
selenium_wrapper_set_options_error = "only accept dict type"
selenium_wrapper_set_argument_error = "only accept str type"
| python |
"""
This module defines the bulk modulus workflow.
"""
from uuid import uuid4
from atomate.utils.utils import get_logger
from atomate.vasp.firetasks.parse_outputs import FitEOSToDb
from atomate.vasp.workflows.base.deformations import get_wf_deformations
from fireworks import Firework, Workflow
from pymatgen.analysis.... | python |
import abc
from torch.nn import Module
class CuriosityModule(abc.ABC, Module):
def __init__(self):
super().__init__()
# self.get_single_intrinsic_reward = single_batch(self.get_intrinsic_reward)
# self.get_single_training_loss = single_batch(self.get_training_loss)
@abc.abstractmeth... | python |
from collections import namedtuple
GamePlayerScores = namedtuple(
'GamePlayerScores',
['assists', 'creep_score', 'deaths', 'kills', 'ward_score']
)
GamePlayerItem = namedtuple(
'GamePlayerItem',
['id', 'name', 'slot', 'can_use', 'consumable', 'count', 'price']
)
GamePlayerRunes = namedtuple(
'Gam... | python |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import os, os.path as path
from .web_server import web_server
from bes.fs.file_util import file_util
from bes.fs.file_path import file_path
from bes.fs.testing.temp_content import temp_content
from bes.archive.temp_archive impo... | python |
from aiohttp import web
from Bubot.Helpers.Helper import Helper
class ReportHandler(web.View):
def __init__(self, request):
web.View.__init__(self, request)
self.obj_type = self.request.match_info.get('objType')
self.obj_name = self.request.match_info.get('objName')
self.report_nam... | python |
# coding: utf-8
"""
Looker API 3.0 Reference
### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token.... | python |
"""
Author: shikechen
Function: Calculate AQI(Air Quality Index)
Version: 1.0
Date: 2019/3/9
"""
def cal_linear(iaqi_lo, iaqi_hi, bp_lo, bp_hi, cp):
iaqi = (iaqi_hi - iaqi_lo) * (cp - bp_lo) / (bp_hi - bp_lo) + iaqi_lo
return iaqi
def cal_pm_iaqi(pm_val):
if 0 <= pm_val < 36:
iaq... | python |
import pytest
from .data import TEST_DATA_ROOT
TEXTGRID_PATHS = sorted(
TEST_DATA_ROOT.glob('wav-textgrid/*.TextGrid')
)
@pytest.fixture
def textgrid_paths():
return TEXTGRID_PATHS
@pytest.fixture(params=TEXTGRID_PATHS)
def a_textgrid_path(request):
return request.param
| python |
__all__ = ['testing']
from .testing import pic1 , pic2 | python |
# Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# 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... | python |
from flask import jsonify
from meli.morse.app.exceptions import ValidationError
from . import api
def bad_request(message):
response = jsonify({'error': 'bad request', 'message': message})
response.status_code = 400
return response
@api.errorhandler(ValidationError)
def validation_error(err):
return... | python |
# Demonstration local server.
# In one window:
# python server.py -D localhost
# In another window:
# python coapget.py -h localhost -v
# python coapget.py -h localhost -u uptime
# python coapget.py -h localhost -u counter
# python coapget.py -h localhost -u unknown
import sys
import coapy.connection
import coapy... | python |
import requests
import sqlite3
import random
from html.parser import HTMLParser
parser = HTMLParser()
connection=sqlite3.connect('previous')
cursor=connection.cursor()
import sys
import json
import discord
from discord.ext import commands
import time
TOKEN = 'NDQwOTMzMjE1NTc5MTQ0MjAz.DmWipQ.p110Y5lhaNCZMYiDYI8mNtghNpk... | python |
"""Decodes and logs angular data from AMS AS5048A."""
# pylint: disable=import-error, import-outside-toplevel, fixme, missing-function-docstring
import argparse
import logging
import os
import time
from typing import Any, List
from meter import Meter
from sensor import Sensor
from volume import Volume
from writer impo... | python |
import shutil
import os.path
def build(source_path, build_path, install_path, targets):
pass
| python |
from watchmen.common.watchmen_model import WatchmenModel
from watchmen.raw_data.rule_schema import RuleType, DSLType
class RuleContext(WatchmenModel):
type: RuleType = None
dsl: DSLType = None
orgId: int = None
orgName: str = None
productId: int = None
productName: str = None
ruleId: int =... | python |
import pytest
from typing import List
from io import BytesIO
from dafni_cli.datasets.dataset_metadata import DataFile, DatasetMetadata
@pytest.fixture
def get_dataset_list_fixture() -> List[dict]:
"""Test fixture for simulating the dataset data return
from calling the get datasets API
Returns:
L... | python |
import argparse
import os
import signal
from typing import Dict, Optional
import numpy as np
import torch
import torchaudio
from loguru import logger
from torch import Tensor, nn
from torch.optim import Adam, AdamW, Optimizer, RMSprop
from torch.types import Number
from df.checkpoint import load_model, read_cp, write... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains Houdini utility functions and classes
"""
from __future__ import print_function, division, absolute_import
import hou
import hdefereval
def get_houdini_version(as_string=True):
"""
Returns version of the executed Houdini
:param as_... | python |
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
from bitmovin_api_sdk.models.dolby_vision_metadata import DolbyV... | python |
# Generated by Django 3.1.13 on 2021-07-30 14:42
import django.core.serializers.json
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
("extras", "0005_configcontext_dev... | python |
#
# Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates
#
# 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 ap... | python |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | python |
import numpy as np
import matplotlib.pyplot as plt
class comparison:
def __init__(self,X_test,y_test):
self.X_test = X_test
self.y_test = y_test
self.predictions_dict = {"True Labels":{"predictions": self.y_test,"threshold": 0.5}}
self.labels_dict = {"True Labels":{"labe... | python |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Seymour
{
public partial class AddFeedDialog : Form
{
public AddFeedDialog()
{
Initializ... | python |
# The Twitter API v2 recent search endpoint provides developers with API access to public Tweets posted over the last week. The endpoint, receiving a single search query and responding with matching Tweets.
import requests, configparser, json
# Read the keys from auth.ini and define them
config = configparser.ConfigP... | python |
import unittest
from query import QueryBuilder
class TestBingoQL(unittest.TestCase):
def setUp(self):
self.builder = QueryBuilder()
def testQueryByPropName(self):
query = self.builder.build_query('"monoisotopic_weight"')
self.assertEquals(u"(elems->>'y' = %(property_term_0)s)", query)... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.