text
string
size
int64
token_count
int64
from logic import * class Agent: def __init__(self): self.matrix = [] self.score = 0 def initialize_game(self): self.score = 0 self.matrix = new_game(4) self.matrix = add_two(self.matrix) self.matrix = add_two(self.matrix) def move(self, direction): ...
758
229
problem_type = "segmentation" dataset_name = "synthia_rand_cityscapes" dataset_name2 = None perc_mb2 = None model_name = "resnetFCN" freeze_layers_from = None show_model = False load_imageNet = True load_pretrained = False weights_file = "weights.hdf5" train_model = True test_model = True pred_model = False debug = Tru...
2,234
896
from bs4 import BeautifulSoup from optimizers.AdvancedJSOptimizer import AdvancedJSOptimizer from optimizers.CSSOptimizer import CSSOptimizer class HTMLParser(object): def __init__(self, html): self.soup = BeautifulSoup(html, 'lxml') def js_parser(self): for script in self.soup.find_all('scri...
583
177
'''Provide interface for game.''' from typing import Any, Dict, List, Optional, Union import flask from flask import Blueprint, url_for from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_sse import sse from werkzeug.wrappers import Response from wtforms import IntegerField...
5,590
1,696
{ "targets": [ { "target_name": "cclust", "sources": [ "./src/heatmap_clustering_js_module.cpp" ], 'dependencies': ['bonsaiclust'] }, { 'target_name': 'bonsaiclust', 'type': 'static_library', 'sources': [ 'src/cluster.c' ], 'cflags': ['-fPIC', '-I', '-pedantic', '...
341
142
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 # #...
4,041
1,252
from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import NoSuchElementException class Supporting: def __init__(self, driver): self.driver = driver self.wait = WebDriverWait(driver, 10) def is_element_present(self, driver, *args): try: ...
514
145
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo class M...
1,516
610
# 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...
2,404
621
import pytest from npRNN.tree_utils import Node, NodeTree def test_merge_results(): #sentence='I know a name of the cat on a hat' sentence='a name of the cat on a hat' words=[Node(word) for word in sentence.split()] tree=NodeTree(words, [0, 5, 3, 1, 2, 0, 0]) assert tree.phrase.name =='(((a name) ...
1,482
594
"""A script is a series of operations.""" import json import os from .ops import create class Script(object): """A script is a series of operations.""" def __init__(self, s=None): """Parse a script from a JSON string.""" if s is not None: self.parsed_script = json.loads(s) ...
1,267
356
from plasTeX import Command, Environment, sourceChildren from plasTeX.Base.LaTeX import Math from plasTeX.Base.TeX.Primitives import BoxCommand # mhchem package - mostly handled by mathjax # Overrive boxcommands inside MathJaX to avoid extra <script type="math/tex"> class MHBoxCommand(BoxCommand): class math(Math....
571
169
""" Totally untested file. Will be removed in subsequent commits """ import tensorflow as tf import matplotlib.image as mpimg import numpy as np from math import ceil, floor import os IMAGE_SIZE = 720 def central_scale_images(X_imgs, scales): # Various settings needed for Tensorflow operation boxes = np.zeros...
5,187
2,027
#!/usr/bin/env python3 # encoding: utf-8 # # (C) 2012-2016 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause """\ Link To The Past - a backup tool Hash functions and commands. """ import hashlib import zlib class CRC32(object): """\ CRC32 API compatible to the hashlib functions (...
1,721
728
#!/usr/bin/env python3.8 table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}" "\N{Devanagari digit two}\N{Devanagari digit three}" "\N{Devanagari digit four}\N{Devanagari digit five}" "\N{Devanagari digit six}\N{Devanagari digit seven}" "\N{Devanagari digit eight}\N{Devanagari digit nine...
360
149
import logging import warnings import pyopencl import pyopencl.array logger = logging.getLogger(__name__) gpu_initialized = False gpu_ctx = None gpu_queue = None def report_devices(ctx): device_names = [d.name for d in ctx.devices] logger.info("initializing opencl context with devices = " + str(device_name...
4,909
1,574
import unittest import numpy as np from astroNN.lamost import wavelength_solution, pseudo_continuum class LamostToolsTestCase(unittest.TestCase): def test_wavelength_solution(self): wavelength_solution() wavelength_solution(dr=5) self.assertRaises(ValueError, wavelength_solution, dr=1) ...
448
161
from django.http import HttpResponse from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser import numpy as np import json import os from .utils.spectrogram_utils import SpectrogramUtils from .utils.feature_extraction_utils impor...
8,265
2,458
# Modules import os import csv #Set up path for file csvpath=os.path.join("..", "Resources", "election_data.csv" ) #print(csvpath) total_votes=0 #total_profit=0 #previous_value=0 #current_value=0 #list_changes=[] print("Election Results") print("---------------------") #Open the csv file with open(csvpath, newline=...
1,416
471
""" Extension to the logging package to support buildlogger. """ # Alias the built-in logging.Logger class for type checking arguments. Those interested in # constructing a new Logger instance should use the loggers.new_logger() function instead. from logging import Logger from . import config from . import buildlo...
367
89
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class AzureCloudCredentials(object): """Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: storage_access_key (string): Specifies the access ...
2,645
645
from utils.utils import * lines = get_input(__file__) lines_as_nums = lines_to_nums(lines) def part1(nums): incr = 0 cur = nums[0] for num in nums: if num > cur: incr += 1 cur = num return incr def part2(): nums = [] for i in range(len(lines_as_nums)): if...
525
222
import datetime import os import sys from google.cloud import firestore from peewee import * sys.path.append(os.getcwd()) home_dir = os.getenv('HOME') db_file_path = os.getcwd() + '/../../data/news_rider.db' print("Reading database from {}".format(db_file_path)) old_db = SqliteDatabase(db_file_path) class NewsIte...
1,170
400
# Copyright 2017 reinforce.io. 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...
1,372
383
# coding=utf-8 # Filename: h5tree.py """ Print the ROOT file structure. Usage: rtree FILE rtree (-h | --help) rtree --version Options: FILE Input file. -h --help Show this screen. """ from __future__ import division, absolute_import, print_function from km3pipe.io.root import open_rfile _...
769
287
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from psychopy.visual import Window, TextStim from psychopy.core import wait, Clock, quit from psychopy.event import clearEvents, waitKeys, Mouse from psychopy.gui import Dlg from time import...
15,952
5,145
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
14,209
4,172
__author__ = 'Riccardo Frigerio' ''' Oggetto HOST Attributi: - mac_address: indirizzo MAC - port: porta a cui e' collegato - dpid: switch a cui e' collegato ''' class Host(object): def __init__(self, mac_address, port, dpid): self.mac_address = mac_address self.port = port self.dpid = dpi...
322
118
from tweepy import OAuthHandler, Stream, API from tweepy.streaming import StreamListener import json import logging import pymongo import config client = pymongo.MongoClient(host='mongo_container', port=27018) db = client.tweets_db auth = OAuthHandler(config.CONSUMER_API_KEY, config.CONSUMER_API_SECRET) auth.set_acc...
2,466
819
from django.db import models from django.utils.translation import ugettext_lazy as _ from assets.models import Item from catalog.models import Inventory CONNECTION_TYPES = ( (1, "Ethernet 1Gb"), (2, "Ethernet 100Mb"), (3, "WIFI"), (4, "Optic Fiber"), (5, "USB"), (6, "HDMI"), (7, "Telephone...
2,028
679
# L1_mpu.py # Author: Roy Kruemcke (roanoake) # 30 NOV 2021 # Allows for the interfacing to the MPU9250 using the smbus2 i2c module # Written for use with Raspberry Pi 4 Model B import smbus2 import numpy as np import data import time # Initialize Register Data CONFIG = 0x1A USER_CTRL = 0x6A PWR_MGMT_1, PWR_MGMT_2 = 0...
3,940
1,581
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import...
1,448
638
from rest_framework.parsers import JSONParser, FileUploadParser from rest_framework.views import APIView from ..models import City from ..models import Country from ..models import University from ..models import Faculty from ..models import Program from rest_framework.decorators import api_view, permission_classes fr...
1,494
400
""" Write a function with a list of ints as a paramter. / Return True if any two nums sum to 0. / >>> add_to_zero([]) / False / >>> add_to_zero([1]) / False / >>> add_to_zero([1, 2, 3]) / False / >>> add_to_zero([1, 2, 3, -2]) / True / """
244
114
""" ASGI config for op_trans project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from op_trans.websocket import webs...
827
264
# -*- coding: utf-8 -*- """API routes config for notifai_recruitment project. REST framework adds support for automatic URL routing to Django, and provides simple, quick and consistent way of wiring view logic to a set of URLs. For more information on this file, see https://www.django-rest-framework.org/api-guide/rou...
482
142
# File to ingest an equities bundle for zipline # Import libraries import pandas as pd import numpy as np def equities_bundle(path_to_file): # Define custom ingest function def ingest(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, ad...
3,786
1,093
import torch import torch.nn as nn class TorchModel(nn.ModuleList): def __init__(self): super(TorchModel, self).__init__() self.linear_1 = nn.Linear(2, 12) self.linear_2 = nn.Linear(12, 1) def forward(self, x): out = self.linear_1(x) out = torch.tanh(out) out = self.linear_2(out) out = torch.sigmo...
343
162
# -*- coding: utf-8 -*- # This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from math import ceil from sql import Select, Column from sql.functions import Function from sql.aggregate import Count from werkzeug.utils impo...
11,529
3,271
from flask import Flask, request, send_file, render_template, url_for import pytube import logging import sys import os from hello import timed_delete from threading import Timer timed_delete() logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) app = Flask(__name__) @app.route("/") def youtube_downloader(): ...
947
315
#!/usr/bin/env python3 # # base.py """ Base functionality. """ # # Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # Based on cyberpandas # https://github.com/ContinuumIO/cyberpandas # Copyright (c) 2018, Anaconda, Inc. # # Redistribution and use in source and binary forms, with or without ...
14,103
5,417
from django.contrib import admin from .models import Agent # Register your models here. class AgentAdmin(admin.ModelAdmin): readonly_fields = ('created','updated') admin.site.register(Agent)
196
52
#!/usr/bin/env python # vim: set et sw=4 sts=4 fileencoding=utf-8: # # A library for reading Microsoft's OLE Compound Document format # Copyright (c) 2014 Dave Hughes <dave@waveform.org.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation f...
4,203
1,429
""" view predication for point cloud, Run valid_one_point_cloud first """ import torch import numpy as np import sys import os import pptk # ------ Configurations ------ # path to pth file pth_file = "../tmp/scene0015_00_vh_clean_2.pth.Random.100" show_gt = False # show groundtruth or not; groudtruth draw ...
3,272
1,856
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0008_grow_owner'), ] operations = [ migrations.CreateModel( name='Measurement', fields=[ ...
1,251
352
import datetime from django.conf import settings from django.db import models from django.utils import translation import tower from babel import Locale, numbers from jingo import env from jinja2.filters import do_dictsort from tower import ugettext as _ import amo from amo.fields import DecimalCharField from amo.he...
7,257
2,110
from kol.request.GenericRequest import GenericRequest class CampgroundRestRequest(GenericRequest): "Rests at the user's campground." def __init__(self, session): super(CampgroundRestRequest, self).__init__(session) self.url = session.serverURL + 'campground.php?action=rest'
301
86
#! /usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of pandas-learn # https://github.com/RichLewis42/pandas-learn # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # Copyright (c) 2015, Rich Lewis <rl403@cam.ac.uk> """ pdlearn.adaptor.methods ~~~~~~~~~~~~~~~~~~~~~~~ Module ...
849
287
# nested loops = The "inner loop" will finish all of it's iterations before # finishing one iteration of the "outer loop" rows = int(input("How many rows?: ")) columns = int(input("How many columns?: ")) symbol = input("Enter a symbol to use: ") #symbol = int(input("Enter a symbol to use: ")) for i in...
396
118
""" .. module:: uwsgi :platform: Any :synopsis: Reads UWSGI stats .. moduleauthor:: Colin Alston <colin@imcol.in> """ import json try: from StringIO import StringIO except ImportError: from io import StringIO from zope.interface import implementer from twisted.internet import defer, reactor from twis...
2,516
740
import datetime import importlib import json import logging import math import mimetypes import os import re import sys import uuid import requests from urllib.parse import urljoin from wsgiref.util import FileWrapper from xml.dom import minidom, Node from django.conf import settings from django.core.files.storage ...
22,167
6,523
import datetime from pymongo import MongoClient import pymongo import pprint try: db = MongoClient("mongodb://localhost:27017")["hkust"] f=0.05 try: print("Querying Documents...") listOfCourseWithWaitingListSize = db.course.aggregate([ { "$unwind": "$sections" }, # { "$project": { "newProduct": {"$multi...
9,050
3,775
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_gatewaynode_sensorstickerreading'), ] operations = [ migrations.CreateModel( name='DerivedInta...
2,549
706
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_all_tables(): db.create_all() def initialize_db(app: Flask): db.init_app(app) db.app = app from investing_algorithm_framework.core.models.order_status import OrderStatus from investing_algorithm_framework.core...
901
274
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from .file...
592
132
from db.table import Table from db.study import Study from db.series import Series from pypika.pseudocolumns import PseudoColumn class Patient(Table): name = 'patients' async def sync_db(self): await self.exec(""" CREATE TABLE IF NOT EXISTS patients ( id SERIAL PRIMARY KEY, ...
2,633
824
#!/usr/bin/env python import sys import json def sec2str(seconds): sec_int = int(round(seconds)) hh = sec_int / 3600 mm = (sec_int - hh * 3600) / 60 ss = sec_int - hh * 3600 - mm * 60 return "%d:%02d:%02d" % (hh, mm, ss) if len(sys.argv) != 4: print "Usage:", __file__, "<segment> <text> <json>" print ...
1,424
580
import sys from string import ascii_lowercase as alphabet def generate_neighbours(ws, s): ls, l = set(), len(s) for i in xrange(l + 1): ls.add(s[:i] + s[i + 1 :]) for e in alphabet: ls.add(s[:i] + e + s[i:]) if i < l and e != s[i]: ls.add(s[:i] + e + s[i...
762
292
from sqlalchemy import Column, Integer from sqlalchemy import ForeignKey from sqlalchemy.orm import declarative_base from .base import Base class RelSaleSizeProject(Base): __tablename__ = 'rel_salesizes_projects' id = Column(Integer, primary_key=True) project_id = Column(Integer, ForeignKey('projects.id')...
385
120
from sudoku.constants import SIZE, BOX_SIZE from sudoku import Sudoku class RS(Sudoku): def __init__(self, grade=0, id=None): super().__init__(grade, id) def possible(self, r, c, n): for i in range(0, SIZE): if self.solved[r, i] == n: return False for i in ...
1,415
435
#!/usr/bin/python3 print('Hello world')
40
15
from algoritmia.problems.binpacking.nextfitbinpacker import NextFitBinPacker class FirstFitBinPacker(NextFitBinPacker):#[full def pack(self, w: "IList<Real>", C: "Real") -> "IList<int>": x = [None] * len(w) free = [] for i in range(len(w)): for j in range(len(free)): ...
571
207
https://leetcode.com/problems/word-search/description/
54
18
#!/usr/bin/env python from __future__ import generators import tables, cPickle, time ################################################################################# def is_scalar(item): try: iter(item) #could be a string try: item[:0]+'' #check for string return...
10,754
3,415
""" jinja2content.py ---------------- DONT EDIT THIS FILE Pelican plugin that processes Markdown files as jinja templates. """ from jinja2 import Environment, FileSystemLoader, ChoiceLoader import os from pelican import signals from pelican.readers import MarkdownReader, HTMLReader, RstReader from pelican.utils imp...
2,234
690
import json from tqdm import tqdm from utils import * from alexnet import AlexNet def classify(net, folder_name, resize=(224, 224)): transform = [] if resize: transform.append(torchvision.transforms.Resize(resize)) transform.append(torchvision.transforms.ToTensor()) transform.append...
4,125
1,608
import serial with serial.Serial("/dev/ttyUSB0", 115200) as ser: while 1: for i in range(5): n = ser.read()[0] print("{:x}".format(n)) print("--------")
200
75
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2021 all rights reserved # class Parser: """ The base class for parsers """ # types from .exceptions import ParsingError, SyntaxError, TokenizationError # meta methods def __init__(self, **kwds): # chain u...
578
196
import numpy as np import random import tensorflow as tf from shfl.data_base.data_base import shuffle_rows from shfl.data_distribution.data_distribution_sampling import SamplingDataDistribution class NonIidDataDistribution(SamplingDataDistribution): """ Implementation of a non-independent and identically dis...
5,087
1,430
# -*- encoding: utf-8 -*- ''' @Time : 2021-06-08 @Author : EvilRecluse @Contact : https://github.com/RecluseXU @Desc : 增 ''' # here put the import lib from pymongo import MongoClient from bson import ObjectId connection: MongoClient = MongoClient('mongodb://localhost:27017') collection = connection['l...
1,298
721
#!/usr/bin/env python3 import hashlib import os import shutil import subprocess import sys import time def doexit(msg, errcode=0): print(msg) input('Press Enter to continue...') sys.exit(errcode) if not os.path.isfile('NAND.bin'): doexit('NAND.bin not found.', errcode=1) if os.path.isfile('firm0fi...
4,428
1,717
import concurrent import time import math import sys import asyncio import logging from . import msg from .parse_error import ParseError from . import DEBUG_LEVEL logger = logging.getLogger(__name__) logger.setLevel(DEBUG_LEVEL) async def _wait_closed(stream): assert(sys.version_info.major >= 3) if sys.versi...
6,329
1,757
from common_clustering import CommonClustering #■clustering_features = CommonClustering(r'C:\Users\ivangarrera\Desktop\T2_cleaned.csv') clustering_features = CommonClustering('D:\Ing. Informatica\Cuarto\Machine Learning\T2_cleaned_gyroscope.csv') attr = list(clustering_features.data_set)[0][:list(clustering_features....
2,182
763
from blacklist import BLACKLIST from flask import Flask, jsonify from flask_restful import Api from resources.hotel import Hoteis, Hotel from resources.user import User, UserLogin, UserLogout, UserRegister, Users from resources.site import Site, Sites from flask_jwt_extended import JWTManager app = Flask(__name__) ap...
1,483
542
# -*- coding: utf-8 -*- """Top-level package for Music Downloader Telegram Bot.""" # version as tuple for simple comparisons VERSION = (0, 9, 16) __author__ = """George Pchelkin""" __email__ = 'george@pchelk.in' # string created from tuple to avoid inconsistency __version__ = ".".join([str(x) for x in VERSION])
316
117
import struct import pycom import time from network import LoRa def blink(seconds, rgb): pycom.rgbled(rgb) time.sleep(seconds) pycom.rgbled(0x000000) # off def setUSFrequencyPlan(lora): """ Sets the frequency plan that matches the TTN gateway in the USA """ # remove all US915 channels for c...
4,355
1,443
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] cudnn_benchmark = True norm_cfg = dict(type='BN', requires_grad=True) checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k...
2,980
1,179
#!/usr/bin/env python import datetime import mock import mom class ExampleClass(mom.Model): JSON_SCHEMA = { '$schema': 'http://json-schema.org/schema#', 'title': 'Test class for JSON', 'type': 'object', 'properties': { 'value_datetime': {'type': ['datetime', 'null']}...
2,265
732
import os import json STOPWORDS_JSON_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, "corpora/stopwords.json" ) with open(STOPWORDS_JSON_PATH, "r", encoding="utf-8") as f: STOPWORD = json.load(f)["stopwords"]
247
103
from __future__ import absolute_import, division, print_function import pytest from .. import message as msg def test_invalid_subset_msg(): with pytest.raises(TypeError) as exc: msg.SubsetMessage(None) assert exc.value.args[0].startswith('Sender must be a subset') def test_invalid_data_msg(): ...
652
203
# -*- coding: utf-8 -*- import os import util from fabric.api import * from fabric.state import output from fabric.colors import * from base import BaseTask from helper.print_helper import task_puts class CollectConfig(BaseTask): """ collect configuration """ name = "collect" def run_task(self, *args, **kwa...
1,358
470
# Copyright (c) 2020 PaddlePaddle 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 appli...
2,334
756
import argparse import os import shutil from tqdm import tqdm import logging from src.utils.common import read_yaml, create_directories import random from src.utils.model import log_model_summary import tensorflow as tf STAGE= "Base Model Creation" logging.basicConfig( filename=os.path.join("logs",'running_logs....
2,183
741
import unittest # https://docs.python.org/3/library/unittest.html from modules.calculator import Calculator as Calc class TestCalculator(unittest.TestCase): """ Test Driven Development Unittest File Module: Calculator Updated: 12/16/2019 Author: Kida Toy """ def test_addition(self): ...
3,774
1,491
#!/usr/bin/env python3 # # main.py # # Command-line utility for interacting with PSU Controller in PDDF mode in SONiC # try: import sys import os import click from tabulate import tabulate from utilities_common.util_base import UtilHelper except ImportError as e: raise ImportError("%s - require...
9,315
3,168
from rest_framework import serializers from versatileimagefield.serializers import VersatileImageFieldSerializer from .models import Image, AnimatedGif class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image',) image = VersatileImageFieldSerializer( ...
758
215
# # coordmap.py -- coordinate mappings. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # from ginga import trcalc from ginga.util import wcs from ginga.util.six.moves import map __all__ = ['CanvasMapper', 'DataMapper', 'OffsetMapper', 'WCSMapper'] class ...
4,930
1,786
# coding: utf-8 # Copyright (c) 2021 PaddlePaddle 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 # Un...
6,658
2,306
import os from . import common import cv2 import numpy as np import imageio import torch import torch.utils.data as data class Video(data.Dataset): def __init__(self, args, name='Video', train=False, benchmark=False): self.args = args self.name = name self.scale = args.scale self...
1,204
408
from .contact_submission_resource import ContactSubmissionResource
67
15
# -*- coding: utf-8 -*- # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
6,395
1,956
from OBlog import database as db from flask import g, current_app import re def getPages(): if not hasattr(g, "getPages"): res = db.query_db('select * from pages;') res.sort(key=lambda x: int(x["idx"])) g.getPages = res return g.getPages def getPagesDict(): if not has...
2,756
1,009
#!/usr/bin/env python # $Id: Compiler.py,v 1.148 2006/06/22 00:18:22 tavis_rudd Exp $ """Compiler classes for Cheetah: ModuleCompiler aka 'Compiler' ClassCompiler MethodCompiler If you are trying to grok this code start with ModuleCompiler.__init__, ModuleCompiler.compile, and ModuleCompiler.__getattr__. Meta-Data ==...
78,232
22,323
# -*- coding: utf-8 -*- import compat import unittest import sys from plmn.utils import * from plmn.results import * from plmn.modem_cmds import * from plmn.simple_cmds import * class SimpleCmdChecks(unittest.TestCase): def test_simple_status_cmd(self): SimpleCmds.simple_status_cmd() assert Resul...
1,267
402
# 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 agreed to in...
13,877
4,011
from plash.eval import eval, register_macro, shell_escape_args @register_macro() def defpm(name, *lines): 'define a new package manager' @register_macro(name, group='package managers') @shell_escape_args def package_manager(*packages): if not packages: return sh_packages =...
1,208
436
from typing import Optional, List from pydantic import BaseModel, EmailStr from . import result class EmailBase(BaseModel): email: Optional[EmailStr] = None class EmailSend(EmailBase): msg: str class EmailResult(BaseModel): pre_header: Optional[str] = None begin: Optional[str] = None content:...
371
113
from rankedchoicevoting import Poll candidatesA = {"Bob": 0, "Sue": 0, "Bill": 0} #votes in array sorted by first choice to last choice votersA = { "a": ['Bob', 'Bill', 'Sue'], "b": ['Sue', 'Bob', 'Bill'], "c": ['Bill', 'Sue', 'Bob'], "d": ['Bob', 'Bill', 'Sue'], "f": ['Sue', 'Bob', 'Bill'] } el...
470
205
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- author: Alex -*- from Centos6_Bit64 import * from SystemUtils import * # Checking version of OS should happened before menu appears # Check version of CentOS SystemUtils.check_centos_version() # Clear screen before to show menu os.system('clear') answer = True whi...
2,422
746
import asyncio import os import time from dataclasses import dataclass import requests_unixsocket from aiohttp import ClientSession, web @dataclass(frozen=True) class Replica: replica_id: str ip: str is_self: bool def replicas_discovery(): session = requests_unixsocket.Session() number_of_repli...
1,923
633