text
string
size
int64
token_count
int64
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.training import session_run_hook from tensorflow.python.training.basic_session_run_hooks import NeverTriggerTimer, SecondOrStepTimer from tensorflow.python.training.session_run_hook impor...
2,516
786
from flask import request from flask_restful import Resource from utils.gatekeeper import allowed_params class DummyResource(Resource): dummy_params = set() @allowed_params(dummy_params) def put(self): return request.json
245
69
#!/usr/bin/env python3 import socket, threading from queue import Queue import sys, struct # NOTE: Use this path to create the UDS Server socket SERVER_SOCKET_PATH = "./socket"; class Result: def __init__(self): self._evt = threading.Event() self._result = None def set_result(self, value...
3,999
1,224
from .rohon_gateway import RohonGateway
40
16
from django.conf.urls import patterns, url, include from .views import force_desktop_version, return_to_mobile_version app_name = 'mobile' urlpatterns = [ # force desktop url(r'^force-desktop-version/$', force_desktop_version, name='force_desktop_version'), # return to mobile version url(r'^return-to...
1,283
471
""" Calibrate with the ROS package aruco_detect """ import rospy import roslib from geometry_msgs.msg import Transform class ROSArUcoCalibrate: def __init__(self, aruco_tag_len=0.0795): print("Please roslaunch roslaunch aruco_detect aruco_detect.launch before you run!") self.aruco_tf_topic = "/f...
698
269
""" * Copyright 2019 EPAM Systems * * 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,...
3,977
1,226
from __future__ import absolute_import __author__ = 'marafi' def SolutionAlgorithim(OData, Dt, Tol, Steps): #Insert within the While loop, make sure parameter "ok" is defined import OpenSeesAPI OData.AddObject(OpenSeesAPI.TCL.TCLScript('if {$ok != 0} {')) OData.AddObject(OpenSeesAPI.TCL.TCLScript('put...
20,287
8,416
import re from argparse import ArgumentParser from multiprocessing import Pool, Manager, Process from pathlib import Path from .utils import UnityDocument YAML_HEADER = '%YAML' class UnityProjectTester: """ Class to run tests on a given Unity project folder """ AVAILABLE_COMMANDS = ('test_no_yaml_is...
6,193
1,674
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 m, n = len(matrix), len(matrix[0]) dp = [[0]*n for _ in range(m)] res = 0 for i in range(m): dp[i][0] = int(matrix[i][0]) for j in range(n): dp[0][...
582
222
# -*- coding: utf-8 -*- # Copyright (c) Polyconseil SAS. All rights reserved. import hashlib import json import logging import os import re from .html import html_config, HtmlHarvester # pylint: disable=unused-import from .sphinx import ( # pylint: disable=unused-import sphinx_config, sphinx_rtd_config, Sph...
3,767
1,048
__all__ = ["stringmethod"]
27
10
# Generated by Django 2.0.4 on 2019-05-21 16:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('carPooling', '0017_carpoolingrecunbook'), ] operations = [ migrations.AlterField( model_name='carpoolinguserconf', n...
855
288
import discord import logging TRADING_API_URL='https://cloud.iexapis.com/stable/stock/{0}/quote' TRADING_API_ICON='https://iextrading.com/favicon.ico' def ticker_embed(symbol): ticker = discord.Embed(title=f"{symbol}".upper(), type="rich", color=3029236, url=TRADING_API_URL.format(symbol)) ticker.set_author(n...
357
142
import bz2 import csv import collections import math from enum import Enum class Select(Enum): FIRST = 'first' RANGE_KEY = 'range_key' RANGE_VALUE = 'range_value' class SelectPolicy: def __init__(self, policy, field=None): self.policy = policy self.field = field class StateSet: ...
9,769
2,781
DEBUG = True TESTING = False
29
10
from hpcrocket.core.filesystem import Filesystem, FilesystemFactory from hpcrocket.core.launchoptions import Options from hpcrocket.pyfilesystem.localfilesystem import LocalFilesystem from hpcrocket.pyfilesystem.sshfilesystem import SSHFilesystem class PyFilesystemFactory(FilesystemFactory): def __init__(self, o...
665
183
import csv import random import cassandra from cassandra.cluster import ResultSet from typing import List class DummyColorMap(object): def __getitem__(self, *args): return '' def csv_rows(filename, delimiter=None): """ Given a filename, opens a csv file and yields it line by line. """ ...
4,053
1,270
# Copyright 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" file accompan...
5,394
1,790
import subprocess proc = subprocess.Popen(['python3', 'articlekeywords.py', 'aih.txt' , '5'], stdout=subprocess.PIPE ) #print(type(proc.communicate()[0])) # path = '/opt/mycroft/skills/mycroft-bitcoinprice-skill/' text = proc.stdout.read() rows = text.splitlines() #print(text.splitlines()) count = 0 s = "" for ...
827
327
# Python 2.7.1 import RPi.GPIO as GPIO from twython import Twython import time import sys import os import pygame APP_KEY='zmmlyAJzMDIntLpDYmSH98gbw' APP_SECRET='ksfSVa2hxvTQKYy4UR9tjpb57CAynMJDsygz9qOyzlH24NVwpW' OAUTH_TOKEN='794094183841566720-BagrHW91yH8C3Mdh9SOlBfpL6wrSVRW' OAUTH_TOKEN_SECRET='d0Uucq2dkSHrFHZGLM1...
4,509
1,708
# Copyright © 2019 Arm Ltd. All rights reserved. # Copyright 2020 NXP # SPDX-License-Identifier: MIT import os import tarfile import pyarmnn as ann import shutil from typing import List, Union from pdoc.cli import main package_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') d...
1,856
688
__author__ = 'jeffye' def sum_consecutives(s): i = 1 li = [] if i < len(s): n = 1 while s[i] != s[i + 1] and s[i] != s[i - 1]: sum = s[i] i = i + 1 return sum while s[i] == s[i + 1]: n = n + 1 sum = s[i] * n i = i + 1 return sum ...
969
381
class term(object): # Dados de cadastro das usinas termeletrica (presentes no TERM.DAT) Codigo = None Nome = None Potencia = None FCMax = None TEIF = None IP = None GTMin = None # Dados Adicionais Especificados no arquivo de configuracao termica (CONFT) Sist = None Status = ...
565
196
"""plerr entrypoint""" from plerr import cli if __name__ == '__main__': cli.main()
88
33
import sys import time from datetime import datetime from bot import FbMessengerBot if __name__ == "__main__": if len(sys.argv) < 3: print("No email or password provided") else: bot = FbMessengerBot(sys.argv[1], sys.argv[2]) with open("users.txt", "r") as file: users = dict...
817
264
# 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, software # distributed under t...
4,361
1,429
from boa3.builtin import public from boa3.builtin.interop.contract import destroy_contract @public def Main(): destroy_contract()
136
46
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl import functools as fnt import logging impo...
4,363
1,757
import collections def canonicalize(json_obj, preserve_sequence_order=True): """ This function canonicalizes a Python object that will be serialized as JSON. Example usage: json.dumps(canonicalize(my_obj)) Args: json_obj (object): the Python object that will later be serialized as JSON. Re...
881
246
from datasette import hookimpl from datasette.utils import detect_spatialite from shapely import wkt def get_spatial_tables(conn): if not detect_spatialite(conn): return {} spatial_tables = {} c = conn.cursor() c.execute( """SELECT f_table_name, f_geometry_column, srid, spatial_index_...
1,170
346
""" Message context. """ from typing import Dict from microcosm.api import defaults, typed from microcosm.config.types import boolean from microcosm_logging.decorators import logger from microcosm_pubsub.constants import TTL_KEY, URI_KEY from microcosm_pubsub.message import SQSMessage @defaults( enable_ttl=typ...
1,440
455
import os import argparse import torch import torch.optim as optim import torchvision import torchvision.transforms as transforms from model import Net from azureml.core import Run run = Run.get_context() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--data_path', ...
2,185
774
import pytest from app.db import session_scope pytestmark = pytest.mark.asyncio async def test_engine_configured(env): async with session_scope() as session: assert str(session.bind.engine.url) == env("SQLALCHEMY_DATABASE_URI")
244
81
from abc import ABC, abstractmethod from datetime import datetime import json import logging from catalyst import utils from catalyst.core import _State class MetricsFormatter(ABC, logging.Formatter): """ Abstract metrics formatter """ def __init__(self, message_prefix): """ Args: ...
3,063
849
#!/usr/bin/env python3 """ Description: Python script to append the common columns in one sheet from another sheet using fuzzy matching. """ import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) import os import sys im...
7,612
2,224
from .Panel import * __all__ = ['BubblePanel'] default_size = plt.matplotlib.rcParams['lines.markersize']**2 class BubblePanel(Panel): ''' BubblePanel is a general wrapper for making scatter plots where planets are represented as bubbles that can have informative sizes and/or colors. ''' def...
9,770
2,551
import os from twisted.internet.defer import succeed class Load(object): def register(self, sysinfo): self._sysinfo = sysinfo def run(self): self._sysinfo.add_header("System load", str(os.getloadavg()[0])) return succeed(None)
264
86
from rest_framework import viewsets from boh import models from . import serializers class OrganizationViewSet(viewsets.ModelViewSet): queryset = models.Organization.objects.all() serializer_class = serializers.OrganizationSerializer class ApplicationViewSet(viewsets.ModelViewSet): queryset = models.A...
675
186
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot import agentframework import csv import matplotlib.animation #create environment in which agents will operate environment=[] #read csv downloaded file f = open('in.txt', newline='') reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) for row in ...
2,207
741
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # try: import e2e.fixtures from e2e.conftest_utils import * # noqa from e2e.conftest_utils import pytest_addoption as _e2e_pytest_addoption # noqa from e2e import config # noqa from e2e.utils import get_plugins_...
2,027
739
"""Validation for UDFs. Warning: This is an experimental module and API here can change without notice. DO NOT USE DIRECTLY. """ from inspect import Parameter, Signature, signature from typing import Any, Callable, List import ibis.common.exceptions as com from ibis.expr.datatypes import DataType def _parameter_c...
2,418
678
import inspect from ariadne import make_executable_schema, QueryType, MutationType, SubscriptionType from .resolver import * # # Schema # class GrammarError(Exception): pass keywords = ['query', 'mutation', 'subscription', 'source'] class SchemaMetaDict(dict): ''' Dictionary that allows decorated sche...
5,629
1,629
import random from otp.ai.AIBase import * from direct.distributed.ClockDelta import * from toontown.battle.BattleBase import * from toontown.battle.BattleCalculatorAI import * from toontown.toonbase.ToontownBattleGlobals import * from toontown.battle.SuitBattleGlobals import * from pandac.PandaModules import * from too...
78,616
24,219
# Copyright (c) Group Three-Forest SJTU. All Rights Reserved. from tracking.tracking import * # a = tracking_video_rectangle("video/","1.mp4",[[273,352],[266,616],[412,620],[416,369]]) a = tracking_video_rectangle_tovideo("video/","1.mp4", "1.png", [[273,352],[266,616],[412,620],[416,369]], result = 'result__.a...
371
177
import gym from gym import spaces, error, utils from gym.utils import seeding import numpy as np from scipy.spatial.distance import pdist, squareform import configparser from os import path import matplotlib.pyplot as plt from matplotlib.pyplot import gca font = {'family' : 'sans-serif', 'weight' : 'bold', ...
11,102
3,929
# -*-coding:utf-8-*- # from functools import reduce from functools import reduce SANCAI_jixiang = [1, 3, 5, 7, 8, 11, 13, 15, 16, 18, 21, 23, 24, 25, 31, 32, 33, 35, 37, 39, 41, 45, 47, 48, 52, 57, 61, 63, 65, 67, 68, 81] # 吉祥运暗示数(代表健全,幸福,名誉等) SANCAI_xiaoji = [6, 17, 26, 27, 29, 30,...
2,127
1,707
# Generated by Django 3.1.2 on 2020-10-18 16:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20201018_1902'), ] operations = [ migrations.AddField( model_name='labourer', name='allproj', ...
406
150
""" Module for reporting into http://www.blazemeter.com/ service Copyright 2015 BlazeMeter 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 Unles...
27,897
8,283
""" Losses that assume an underlying spatial organization (gradients, curvature, etc.) """ import torch import torch.nn as tnn from nitorch.core.pyutils import make_list, prod from nitorch.core.utils import slice_tensor from nitorch.spatial import diff1d from ._base import Loss class LocalFeatures(tnn.Module): "...
20,434
6,069
from django.db import models from django.utils import timezone class Categoria(models.Model): nome = models.CharField(max_length=255) def __str__(self): return self.nome class Item(models.Model): nome = models.CharField(max_length=255) data_criacao = models.DateTimeField(default=timezone.no...
607
200
from app.services.console import Console from app.services.server import Server __main__ = ["server", "console"]
114
31
#!/usr/bin/env python3 # Copyright 2020 Gaitech Korea 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 appli...
2,801
752
import sys import unittest import requests_mock from mock import patch sys.path.append('services/LiveService') from LiveService import LiveService L = LiveService() baseURL = "https://yanexx65s8e1.live.elementalclouddev.com/api" class LiveServiceTest(unittest.TestCase): '''@patch('services.LiveService.LiveSe...
5,298
1,902
# -*- coding: utf-8 -*- """ Created on Fri Sep 14 11:49:10 2018 @author: Lionel Massoulard """ import pytest import numpy as np import pandas as pd from sklearn.base import is_regressor, is_classifier from sklearn.exceptions import NotFittedError from sklearn.model_selection import KFold from sklearn.ensemble impo...
10,005
3,968
from django import forms from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, Http404 from manager import models as pmod from . import templater from django.conf import settings import decimal, datetime # This view will display all users and then on a new page display al...
1,611
574
import pandas as pd import numpy as np import os import logging # suppress warnings import warnings; warnings.filterwarnings('ignore'); from tqdm.autonotebook import tqdm # register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` tqdm.pandas() # https://pandas.pydata.org/pandas-docs/stable/user_g...
1,521
497
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class PyCyvcf2(PythonPackage): """fast vcf parsing with cython + htslib""" homepage...
828
365
""" GPA Calculator """ # Write a function called "simple_gpa" to find GPA when student enters a letter grade as a string. Assign the result to a variable called "gpa". """ Use these conversions: A+ --> 4.0 A --> 4.0 A- --> 3.7 B+ --> 3.3 B --> 3.0 B- --> 2.7 C+ --> 2.3 C --> 2.0 C- --> 1.7 D+ --> 1.3 D --> 1.0 D- -->...
340
163
import sys import soundcard import numpy import pytest ones = numpy.ones(1024) signal = numpy.concatenate([[ones], [-ones]]).T def test_speakers(): for speaker in soundcard.all_speakers(): assert isinstance(speaker.name, str) assert hasattr(speaker, 'id') assert isinstance(speaker.channels...
5,283
1,805
# This is a simple program to find the last three digits of 11 raised to any given number. # The main algorithm that does the work is on line 10 def trim_num(num): if len(str(num)) > 3: # no need to trim if the number is 3 or less digits long return str(num)[(len(str(num)) - 3):] # trims the number ret...
623
213
#!/usr/bin/env python import time from osr_msgs.msg import Joystick, Commands, Encoder, RunStop from nav_msgs.msg import Odometry from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3 import rospy import tf import math import numpy class Odometry2(): def __init__(self, baseFrame, wheelTrack, mpt, d...
6,137
2,262
import numpy as np import h5py import os from devito.logger import info from devito import TimeFunction, clear_cache from examples.seismic.acoustic import AcousticWaveSolver from examples.seismic import Model, RickerSource, Receiver, TimeAxis from math import floor from scipy.interpolate import griddata import argparse...
4,199
1,870
import math if __name__=='__main__': n=(int)(input()) for abc in range(n): t=(int)(input()) print math.factorial(t)
154
54
from setuptools import setup setup(name="pykinematicskineticstoolbox", version="0.0", description="Installable python package which collects useful kinematics and kinetics functions", author="John Martin K. Godø", author_email="john.martin.kleven.godo@gmail.com", license="MIT", packages=["pykinematic...
373
128
from datetime import datetime # ensure an rpc peer is added def addpeer(p, rpcpeer): pid = rpcpeer['id'] if pid not in p.persist['peerstate']: p.persist['peerstate'][pid] = { 'connected': rpcpeer['connected'], 'last_seen': datetime.now() if rpcpeer['connected'] else None, ...
1,251
453
# terrascript/dns/r.py import terrascript class dns_a_record_set(terrascript.Resource): pass class dns_aaaa_record_set(terrascript.Resource): pass class dns_cname_record(terrascript.Resource): pass class dns_mx_record_set(terrascript.Resource): pass class dns_ns_record_set(terrascript.Resource...
505
192
from Jumpscale import j from .TCPRouterClient import TCPRouterClient JSConfigs = j.baseclasses.object_config_collection class TCPRouterFactory(JSConfigs): __jslocation__ = "j.clients.tcp_router" _CHILDCLASS = TCPRouterClient def test(self): """ kosmos 'j.clients.tcp_router.test()' ...
749
239
""" Functions for reading Magritek Spinsolve binary (dx/1d) files and parameter (acqu.par/proc.par) files. """ import os from warnings import warn import numpy as np from . import fileiobase from . import jcampdx __developer_info__ = """ Spinsolve is the software used on the Magritek benchtop NMR devices. A spect...
8,837
2,825
import logging import copy import pickle import pandas as pd class BaseClass: def __init__(self, input_data: pd.DataFrame, logger: logging.Logger, metadata: dict): self.__input_data = input_data self.__logger = logger self.__metadata = met...
21,781
6,174
import sys import scipy.stats normal = scipy.stats.norm(0, 1) def phi_major(x): return normal.cdf(x) def phi_minor(x): return normal.pdf(x) def v(x, t): xt = x - t denom = phi_major(xt) return -xt if (denom < sys.float_info.epsilon) else phi_minor(xt) / denom def w(x, t): xt = x - t ...
946
442
# -*- coding: utf-8 -*- # # Graph : graph package # # Copyright or Copr. 2006 INRIA - CIRAD - INRA # # File author(s): Jerome Chopard <jerome.chopard@sophia.inria.fr> # # Distributed under the Cecill-C License. # See accompanying file LICENSE.txt or copy at # http://www.cecill.in...
14,189
4,063
import paddle.fluid as fluid from paddle.fluid.initializer import MSRA from paddle.fluid.param_attr import ParamAttr class MobileNetV2SSD: def __init__(self, img, num_classes, img_shape): self.img = img self.num_classes = num_classes self.img_shape = img_shape def ssd_net(self, scale=...
8,439
2,403
""" Copyright 2020 The OneFlow 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 law or agr...
5,844
2,102
#! /usr/bin/env python3 import json import os.path import jinja2 DEFAULT_PARAMS = { "ansible_user": "vagrant" } if __name__ == "__main__": # Reading configuration here = os.path.dirname(os.path.realpath(__file__ + "/../")) with open(here + "/config.json", "r") as rf: config = json.load(rf...
1,767
581
import os import harvest.dataframe from harvest.models.simulator import Simulator class BeastSimulator(Simulator): def __init__(self, tree, n_features): Simulator.__init__(self, tree, n_features) def generate_beast_xml(self): # Subclasses should implement this return None def ge...
883
261
# pylint: skip-file import os from assimilator import * from Boinc import boinc_project_path class SlimeClustersAssimilator(Assimilator): def __init__(self): Assimilator.__init__(self) def assimilate_handler(self, wu, results, canonical_result): if canonical_result == None: return...
770
262
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
12,343
3,379
from astropy.table import Table, Column import matplotlib.pyplot as plt #url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&select=pl_hostname,ra,dec&order=dec&format=csv" url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets" # This...
1,527
687
class KunaError(Exception): pass class AuthenticationError(KunaError): """Raised when authentication fails.""" pass class UnauthorizedError(KunaError): """Raised when an API call fails as unauthorized (401).""" pass
242
78
from tools import factorial def solve(): fa = tuple(factorial(x) for x in range(10)) def _sum_factorial_of_digits(n: int) -> int: s = 0 while n > 0: s += fa[n % 10] n //= 10 return s limit = 1000000 loops = [0 for x in range(limit)] for i in range(...
792
272
# Copyright 2022. ThingsBoard # # 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 ...
27,966
7,350
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ### CONTROLS (non-tunable) ### # general TYPE_OF_RUN = test_episodes # train, test, test_episodes, render NUM_EPISODES_TO_TEST = 1000 MIN_FINAL_REWARD_FOR_SUCCESS = 1.0 LOAD_MODEL_FROM = models/gru_flat_babyai.pth SAVE_MODELS_TO = None # wo...
966
510
"""runghc support""" load(":private/context.bzl", "render_env") load(":private/packages.bzl", "expose_packages", "pkg_info_to_compile_flags") load( ":private/path_utils.bzl", "link_libraries", "ln", "target_unique_name", ) load( ":private/set.bzl", "set", ) load(":providers.bzl", "get_ghci_extr...
3,474
1,184
# Copyright (C) 2019 Cancer Care Associates # 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 ...
8,456
2,671
"""Test data validator decorator.""" from unittest.mock import Mock from aiohttp import web import voluptuous as vol from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator async def get_client(aiohttp_client, validator): """Gener...
1,929
572
import days STAGE_INIT = 0 STAGE_CHALLENGE_INIT = 1 STAGE_BOOKED = 2 def createJSONTemplate(data): pass messages = [ "Hey {{first_name}}, thankyou for your enquiry to be one of our Transformation Challengers", "We have 2 Challenges available for you:\n\nThe 8 Week Bikini Challenge which h...
7,410
2,166
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class Pagmo2(CMakePackage): """Parallel Global Multiobjective Optimizer (and its Python ...
1,349
504
#!/usr/bin/env python3 import os, sys, re, json, requests, datetime, tarfile, argparse from pprint import pprint import numpy as np from utils.UrlUtils import UrlUtils server = 'https://qc.sentinel1.eo.esa.int/' cal_re = re.compile(r'S1\w_AUX_CAL') def cmdLineParse(): ''' Command line parser. ''' ...
4,984
1,701
# Copyright 2005-2008, James Garrison # Copyright 2010, 2012 Bradley M. Kuhn # This software's license gives you freedom; you can copy, convey, # propagate, redistribute, modify and/or redistribute modified versions of # this program under the terms of the GNU Affero General Public License # (AGPL) as published by the...
2,590
907
import unittest from unittest.mock import Mock from graphene import Schema from graphene.test import Client from graphene_spike.query import Query class MainTest(unittest.TestCase): def setUp(self): self.schema = Schema(query=Query) self.client = client = Client(self.schema) def test_hello_...
1,430
448
from rich import print from rich.console import Console from rich.table import Table import click from click_default_group import DefaultGroup import yaml import os ##from terminaltables import SingleTable import sys from textwrap import wrap import collections import datetime import configparser import pkg_resources ...
10,028
3,240
from social_core.backends.oauth import BaseOAuth2 class RagtagOAuth2(BaseOAuth2): """Ragtag ID OAuth authentication backend""" name = "ragtag" AUTHORIZATION_URL = "https://id.ragtag.org/oauth/authorize/" ACCESS_TOKEN_URL = "https://id.ragtag.org/oauth/token/" ACCESS_TOKEN_METHOD = "POST" REVO...
1,330
443
from django.db import models from django.contrib import admin class Provider(models.Model): name = models.CharField(max_length=50) domain = models.CharField(max_length=50) class Meta: ordering = ['name'] app_label = 'api' def __str__(self): return self.domain @admin.registe...
409
126
#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String from gazebo_msgs.msg import LinkState def talker(): pub = rospy.Publisher('/gazebo/set_link_state', LinkState, queue_size=10) ppp = LinkState() rospy.init_node('talker', anonymous=True) rate = rospy.R...
853
331
import torch from os import listdir, path from PIL import Image import torchvision class DiscriminatorDataset(torch.utils.data.Dataset): def __init__(self): super(DiscriminatorDataset, self).__init__() currentDir = path.dirname(__file__) abstractDir = path.join(currentDir, 'image_data/abs...
1,073
325
from django.core.mail.message import EmailMessage, EmailMultiAlternatives from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string from django.utils.safestring import mark_safe def send_mail_task(subject, message, from_email, recipient_list): message = EmailMessa...
951
278
"""Tests for the HAPServer.""" from socket import timeout from unittest.mock import Mock, MagicMock, patch import pytest from pyhap import hap_server @patch('pyhap.hap_server.HAPServer.server_bind', new=MagicMock()) @patch('pyhap.hap_server.HAPServer.server_activate', new=MagicMock()) def test_finish_request_pops_s...
1,506
488
from flask import render_template, Blueprint, request from app.utils.search import MySQLClient from app.utils.preprocessor import TextPreprocessor mainbp = Blueprint("main", __name__) @mainbp.route("/search", methods=["GET"]) @mainbp.route("/", methods=["GET"]) def home(): stores_by_page = 10 topic = reque...
1,604
498
# -*- coding: utf-8 -*- """This module contains design algorithm for a traditional two stage operational amplifier.""" from typing import TYPE_CHECKING, List, Optional, Dict, Any, Tuple, Sequence from copy import deepcopy import numpy as np import scipy.optimize as sciopt from bag.math import gcd from bag.data.lti...
31,770
11,213