text
string
size
int64
token_count
int64
""" Code for a light curve collection of Agnieszka Cieplak's synthetic signals. """ import re import tarfile import urllib.request import numpy as np import pandas as pd from pathlib import Path from typing import Iterable from ramjet.photometric_database.light_curve_collection import LightCurveCollection class Self...
5,313
1,559
# CompOFA – Compound Once-For-All Networks for Faster Multi-Platform Deployment # Under blind review at ICLR 2021: https://openreview.net/forum?id=IgIk8RRT-Z # # Implementation based on: # Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song ...
2,661
970
class Config(object): DEBUG = False TESTING = False class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' ECHO = False class DevelopmentConfig(Config): DEBUG = True ECHO = False DATABASE_URI = 'sqlite:///:memory:'
266
83
import torchvision.models as models import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import DataLoader import torch #from models_dir.p_s_s.models import duc_hdc, fcn8s, fcn16s, fcn32s, gcn, psp_net, seg_net, u_net from efficientnet_pytorch import Efficien...
17,427
6,265
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params)...
4,548
1,336
from rest_framework import viewsets from .serializers import OrdersSerializer, OrderedItemsSerializer from .models import Order, OrderedItem class OrdersViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = OrdersSerializer queryset = Order.objects.all() permission_classes = [] class Ord...
488
142
import django from apps.stats.models import CountStats from apps.stddata.models import Language, Country django.setup() if CountStats.objects.filter(language__isnull=False).count() == 0: for i in Language.objects.all(): CountStats.objects.init_stats(language=i) if CountStats.objects.filter(country__isnu...
462
142
import asyncio from unittest import TestCase from luno_streams import Updater from websockets.protocol import State import logging from concurrent import futures logging.getLogger('luno_streams').addHandler(logging.StreamHandler()) class TestConnection(TestCase): def test_simple_updates(self): num_updat...
1,538
499
#FIFO - first -> first class Queue: def __init__(self): self.queue = [] def isEmpty(self): return self.queue == [] def enqueue(self, data): self.queue.append(data) def dequeue(self): data = self.queue[0] del self.queue[0] return data def peek(self): return self.queu...
580
256
#pj1 threelist = [] fivelist = [] togetherlist = [] sum = 0 for num in range(1000): if num % 3 == 0: threelist.append(num) if num % 5 == 0: fivelist.append(num) togetherlist = threelist for num in fivelist: if not num in togetherlist: togetherlist.append(num) fo...
376
159
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import os import pytest from hmtnote import annotate, dump DATADIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") MULTISAMPLE_VCF = os.path.join(DATADIR, "multisample.vcf") TEST_VCF = os.path.join(DATADIR, "test.vcf") TEST_...
3,925
1,192
from .exposureadjust import ExposureAdjust
42
14
from mrjob.job import MRJob #------------------------------------------------------------------------- ''' Problem 3: In this problem, you will get familiar with the mapreduce framework. In this problem, please install the following python package: * mrjob Numpy is the library for writing Pyt...
2,752
650
import badger2040 from badger2040 import WIDTH TEXT_SIZE = 0.45 LINE_HEIGHT = 16 display = badger2040.Badger2040() display.led(128) display.pen(0) display.rectangle(0, 0, WIDTH, 16) display.thickness(1) display.pen(15) display.text("badgerOS", 3, 8, 0.4) display.pen(0) y = 16 + int(LINE_HEIGHT / 2) display.text("...
870
413
from os import path, terminal_size import json import random import time from ErrorBook import ErrorBook class Game(): def __init__(self, cfg_filename=None) -> None: if cfg_filename == None: self.cfg_filename = path.join('Cfg', 'cfg.json') else: self.cfg_filename = cfg_file...
8,047
2,314
def getNewData(): import requests import json import pandas as pd url = "https://covid-193.p.rapidapi.com/statistics" headers = { 'x-rapidapi-host': "covid-193.p.rapidapi.com", 'x-rapidapi-key': "4c37223acemsh65b1a8b456b72c1p15a99ajsnd4a09ab346a4" } response = requests.request("GET", url, headers=heade...
2,729
1,208
import numpy as np import pandas as pd import argparse from IPython.display import display def main(): parser = argparse.ArgumentParser(description="Imports Indexer for Blue Sentry") parser.add_argument("--output_file", help="File that the imports are indexed to", required=True) parser.add_argument("--inp...
2,026
561
import asyncio import time import aiohttp from throttler import Throttler, ThrottlerSimultaneous class SomeAPI: api_url = 'https://example.com' def __init__(self, throttler): self.throttler = throttler async def request(self, session: aiohttp.ClientSession): async with self.throttler: ...
1,063
338
import os def absoluteFilePaths(directory): path_list = [] for dirpath, _, filenames in os.walk(directory): for f in filenames: path_list.append(os.path.abspath(os.path.join(dirpath, f))) return path_list def create_a_folder(folder_path): if not os.path.exists(folder_path): ...
393
133
from raw_type import raw_type class generator(raw_type): def __init__(self): self.data = [] self.label = [] self.fs = 0 self.lead = 6 self.length = 0 def read_data(self, path): import wfdb import os all_files = os.listdir(path) ...
1,014
366
isDatabaseEnabled = True try: from replit import db except ModuleNotFoundError: isDatabaseEnabled = False import os class colors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' RESET = '\033[0m' BOLD = '\...
981
365
from keras.models import Model from keras.layers import Dense, Dropout, Flatten, Input, Embedding,Bidirectional from keras.layers.merge import Concatenate from keras.layers import LSTM from keras.layers import MaxPooling1D, Embedding, Merge, Dropout, LSTM, Bidirectional from keras.layers.merge import Concatenate fro...
2,054
644
import os import importlib import logging from . import lang_generators KNOWN_GENERATORS = {} def register_generator(lang, module): global KNOWN_GENERATORS KNOWN_GENERATORS[lang] = module def __generate_type(generator, namespace, name, jidl): structure_format = generator.get_structure_format() re...
2,041
659
import static.strings as strings import static.strings_edu as strings_edu from app import ResponseBuilder, AlexaRequest def handle_education(request): """ Generate response to intent type EducateIntent with explanation of the asked investing term. :type request AlexaRequest :return: JSON response incl...
1,269
435
# Generated by Django 2.1.5 on 2019-04-09 10:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('skill', '0004_auto_20190327_2016'), ] operations = [ migrations.RemoveField( model_name='skilli...
652
225
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @License : Copyright(c) 2018 MIT License # @Time : 2019-01-09 15:01 # @Author : YUELONG.CHEN # @Mail : yuelong_chen@yahoo.com # @File : psopen.py # @Software: PyCharm from __future__ import absolute_import, unicode_literals import logging import os import sys...
3,116
1,110
from typing import Union, Dict, List JsonTypes = Union[Dict[str, 'JsonTypes'], List['JsonTypes'], str, int, float, bool, None]
130
43
import requests import time import json url = "https://www.okex.com/api/v5/market/ticker?instId=SHIB-USDT" proxies = { 'https': 'http://127.0.0.1:10809', } headers = { 'Connection': 'close',} requests.packages.urllib3.disable_warnings() requests.adapters.DEFAULT_RETRIES = 1 if __name__ == "__main__": ...
977
345
#!/usr/bin/env python from setuptools import setup, find_packages # Hack to prevent stupid TypeError: 'NoneType' object is not callable error on # exit of python setup.py test # in multiprocessing/util.py _exit_function when # running python setup.py test (see # http://www.eby-sarna.com/pipermail/peak/2010-May...
968
334
from .point_extractor import point_extractor from .point_extractor_by_frame import point_extractor_by_frame from .rectangle_extractor import rectangle_extractor from .question_extractor import question_extractor from .survey_extractor import survey_extractor from .poly_line_text_extractor import poly_line_text_extracto...
1,606
507
# Copyright (C) 2017 Open Information Security Foundation # # You can copy, redistribute or modify this Program under the terms of # the GNU General Public License version 2 as published by the Free # Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; wi...
2,869
971
""" Return the current time in the same format is BigFix Relevance. """ import datetime time_now = datetime.datetime.now(datetime.timezone.utc) print(time_now.strftime("%a, %d %b %Y %H:%M:%S %z"))
198
74
"""Gompertz distribution.""" import numpy from scipy import special from ..baseclass import SimpleDistribution, ShiftScaleDistribution class gompertz(SimpleDistribution): """Gompertz distribution.""" def __init__(self, c): super(gompertz, self).__init__(dict(c=c)) def _pdf(self, x, c): ...
1,751
667
from .shap_model_describer import SHAPModelDescriber # TODO: fix from .enums import Constituency, Aspect from .describer import Describer class Describable: """ A *Trustworthy-AI* interface that defines the capabilities of objects (e.g., `Models`, `Graphs`) that are `Describable, i.e., they can self-desc...
1,433
396
import unittest import os import json as standard_json import example.mini_json, example.macro_json, example.calculator from boozetools.macroparse import compiler from boozetools.parsing import shift_reduce from boozetools.parsing.general import brute_force, gss from boozetools.support import runtime, interfaces, expa...
6,839
2,677
# Generated by Django 2.0.6 on 2019-11-21 13:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('apimb', '0010_auto_20191115_1208'), ] operations = [ migrations.AddField( model_name='runner', ...
488
180
from binascii import hexlify from hashlib import pbkdf2_hmac from flask import Blueprint, Response, request, current_app from flask_restful import Api from app.views.v1 import BaseResource from app.views.v1 import admin_only from app.models.account import SignupWaitingModel, StudentModel, AdminModel api = Api(Blu...
1,668
568
from .bfp import BFP from .channel_mapper import ChannelMapper from .fpg import FPG from .fpn import FPN from .fpn_carafe import FPN_CARAFE from .hrfpn import HRFPN from .nas_fpn import NASFPN from .nasfcos_fpn import NASFCOS_FPN from .pafpn import PAFPN from .rfp import RFP from .yolo_neck import YOLOV3Neck from .glne...
2,103
923
from mapillary_tools.process_import_meta_properties import process_import_meta_properties class Command: name = 'extract_import_meta_data' help = "Process unit tool : Extract and process import meta properties." def add_basic_arguments(self, parser): parser.add_argument( '--rerun', h...
2,713
702
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 12:05:04 2020 @author: ravi """ def TwoPointer(arr): p1 = 0 #points to non-zero p2 = 0 #points to zeros i=0 while(i!=(len(arr)-1)): while(True): if p1>= len(arr): break if arr[p1]...
831
295
class Solution: def searchRange(self, nums, target: int): cnt = len(nums) if not cnt: return [-1, -1] if target > nums[-1] or target < nums[0]: return [-1, -1] start = 0 end = cnt - 1 mid = 0 bound = [-1] * 2 while start < end...
1,064
344
__token__ = 'INSERT BOT TOKEN HERE' __prefix__ = ':' #OPTIONAL Prefix for all commands, defaults to colon __timezone__ = 'Europe/Berlin' #OPTIONAL __botserverid__ = 102817255661772800 #OPTIONAL Specifies the main serverid from which the server-/modlog should be taken + some other nito features __kawaiichannel__ = 2...
766
264
"""Module to test dynamic loading.""" # Define a variable to check its value testvar = 'testval' # Define a function to check its loading and execution def sum(a, b): return a + b
186
54
import time from Servo import Servo # members of each class: # finger: bend, bend_max, straighten_max # hand: straighten_all_fingers, make_fist, move_all_fingers # wrist: rotate # forearm: # shoulder: flex/extend, abduction_up/abduction_down, rotation_internal/rotation_external, rotation_up/rotation_down, # arm: # to...
9,890
3,162
import torch import numpy as np import torch.optim as optim from torch.nn.utils import clip_grad_norm_ import torch.nn.functional as F import random import math from ReplayBuffers import ReplayBuffer, PrioritizedReplay from model import IQN class IQN_Agent(): """Interacts with and learns from the environment.""" ...
17,158
5,506
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' EXPOsan: Exposition of sanitation and resource recovery systems This module is developed by: Yalin Li <zoe.yalin.li@gmail.com> This module is under the University of Illinois/NCSA Open Source License. Please refer to https://github.com/QSD-Group/EXPOsan/blob/mai...
5,162
1,868
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Chris Caron <lead2gold@gmail.com> # All rights reserved. # # This code is licensed under the MIT License. # # 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 th...
1,849
636
#!/usr/bin/env python import sys from PyQt5 import QtGui, QtSvg from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) svgWidget = QtSvg.QSvgWidget('Android_sample.svg') svgWidget.setGeometry(50,50,759,668) svgWidget.show() sys.exit(app.exec_())
265
110
# file : prog_assign_2_ee677_2016_expression_tree_from_robdd_Wed_26_Oct.py # The following code contains the simple classes to model following # types of logic node objects # Binary Boolean Operation node, Not Operation node, Input node, Constant node # Using these classes and the utility function "robdd_to_expr_t...
8,559
3,094
from mongothon import create_model, create_model_offline from pickle import dumps, loads from unittest import TestCase from mock import Mock, ANY, call, NonCallableMock from mongothon import Document, Schema, NotFoundException, Array from mongothon.validators import one_of from mongothon.scopes import STANDARD_SCOPES f...
24,340
7,983
import logging import glob import sys import os import tqdm import torch import numpy as np from torch.utils.tensorboard import SummaryWriter from argparse import ArgumentParser from pfrl.replay_buffers import ReplayBuffer, PrioritizedReplayBuffer from exp import create_md_table_from_dic sys.path.append('../../') f...
10,729
3,550
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test deactivation of sigops counting based on abc-schnorrmultisig-activation.py (D3736). """ from test_framewo...
13,863
4,815
from __future__ import print_function # pypi from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker import zope.sqlalchemy # from sqlalchemy import event # local # import the SqlAlchemy model, which will call `sqlalchemy.orm.configure_mappers` from ... import model # noqa: F401 # ======...
2,912
836
from DeepSaki.initializer.helper.initializer_helper import MakeInitializerComplex
82
22
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): user = request.user # if the user is a staff user (i.e. can log into the admin page), # they can do anything in the API. # Otherwise...
436
130
import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np import matplotlib.pyplot as plt # https://www.tensorflow.org/quantum/tutorials/barren_plateaus#2_generating_random_circuits def generate_circuit(qubits, depth, param): circuit = cirq.Circuit() for qubit in qubi...
3,279
1,277
''' Sast Git Leaks Copyright 2020 Leboncoin Licensed under the Apache License Written by Fabien Martinez <fabien.martinez+github@adevinta.com> ''' from importlib import import_module from pathlib import Path import logging from . import utils LOGGER = logging.getLogger(__name__) def load_tool(variables, tool: dic...
4,160
1,254
'''面试题29:顺时针打印矩阵 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 -------------- Example: input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 output:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10 ''' def print_array_clockwise(array): if array is None or len(array) == 0: return rows = len(array) cols = len(array[0]) ...
1,726
704
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from django.contrib.admin.widgets import FilteredSelectMultiple from django.utils.text import format_lazy from tag_sentenze.models import Judgment from users.models im...
3,679
1,133
from .PageMenu import PageMenu from .Sidebar import Sidebar __all__ = [ "PageMenu", "Sidebar" ]
104
37
# O-19-Marianne Touchie ''' This code will clean the OB datasets and combine all the cleaned data into one Dataset name: O-19-Marianne Touchie 1. one office building 2. Xuezheng processed outdoor and indoor data 3. use the same room ids as Xuezheng used for window and door status data ''' import os import glob impor...
6,175
2,388
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. soma_idade = 0 maior_idade_homem = 0 nome_homem_velho = '' total_mulheres = 0 for a in range(1, 5): nome = str(inp...
1,018
408
import os import gym import ray from ray.rllib.agents import dqn from gym.spaces import Discrete, Box from collections import OrderedDict import pdb import numpy as np import copy from gym.wrappers import Monitor from gym.wrappers.monitoring.stats_recorder import StatsRecorder import numpy as np import minerl class ...
8,333
2,686
import socket import ssl def map4to6(ip): return "::ffff:"+ip def prefixstream(pkt): tcpkt = bytearray() tcpkt.append(len(pkt)//0x100) tcpkt.append(len(pkt)%0x100) tcpkt += pkt return tcpkt def getfromstream(sock): data = sock.recv(0x2) l = data[0] * 0x100 l += data[1] data = sock.recv(l) return data ...
2,765
1,165
from .fund_balances import CashReportFundBalances from .net_cash_flow import CashReportNetCashFlow from .revenue import CashReportRevenue from .spending import CashReportSpending
179
55
""" hubspot lines api """ from typing import Dict, Union from hubspot3.base import BaseClient from hubspot3.crm_associations import CRMAssociationsClient from hubspot3.utils import get_log, prettify, ordered_dict LINES_API_VERSION = "1" class LinesClient(BaseClient): """ Line Items API endpoint :see: ht...
3,756
1,071
import requests from bs4 import BeautifulSoup from util import normalize_str import json import uuid from os import path, makedirs import hashlib from typing import List from activity import Activity from collections import defaultdict class Member: """ Class representing a single member of the parliament ...
6,115
1,788
# -*- coding: utf-8 -*- from quart import url_for, Blueprint, render_template from quart.blueprints import BlueprintSetupState class Apidoc(Blueprint): """ Allow to know if the blueprint has already been registered until https://github.com/mitsuhiko/quart/pull/1301 is merged """ def __init__(self...
1,496
482
#!/usr/bin/env python # coding: utf-8 if __name__ == "__main__": from setuptools import setup setup(name="catalogue")
128
46
from pathlib import Path import torch from torch.optim.lr_scheduler import ExponentialLR import Resources.training as r from Models.erfh5_ConvModel import S80Deconv2ToDrySpotTransferLearning from Pipeline.data_gather import get_filelist_within_folder_blacklisted, \ get_filelist_within_folder from Pipeline.data_loa...
4,329
1,354
import pytest from studying import shipment_factory pytestmark = [pytest.mark.django_db] @pytest.fixture def unship_record(mocker): return mocker.patch('studying.shipment.RecordShipment.unship') @pytest.fixture def unship_course(mocker): return mocker.patch('studying.shipment.CourseShipment.unship') def...
897
301
import pymongo import os from dotenv import load_dotenv import sqlite3 from pprint import pprint load_dotenv() DB_USER = os.getenv("MONGO_USER", default="OOPS") DB_PASSWORD = os.getenv("MONGO_PASSWORD", default="OOPS") CLUSTER_NAME = os.getenv("MONGO_CLUSTER_NAME", default="OOPS") connection_uri = f"mongodb://{DB_US...
1,518
624
import os from io import open from os import path from typing import AnyStr, List from setuptools import setup, find_packages package_dir = path.abspath(path.dirname(__file__)) def _process_requirements() -> List[str]: requirements = [] with open(path.join(package_dir, 'requirements.txt'), encoding='utf-8'...
2,666
814
''' Author: fgg Date: 2022-05-26 16:16:45 LastEditors: fgg LastEditTime: 2022-05-26 16:45:45 FilePath: \python_study_2022\kyhg\kyhg\spiders\trans.py Description: 学习用文件,主要就是笔记和随笔 Copyright (c) 2022 by fgg/Mechanical Design Studio, All Rights Reserved. ''' import json import tablib import csv # 获取json数据 with open('kyhg...
921
511
import numpy as np import matplotlib.pyplot as plt def build_fitfunction_from_dict(func_dict): # build the def part of the method def_part = "def general_function(x" number_of_parameters = len(func_dict['start-values']) for val,num in zip(func_dict['start-values'], range(number_of_parameters)): ...
738
259
import csv import random from functools import partialmethod import torch import numpy as np from sklearn.metrics import precision_recall_fscore_support, \ precision_recall_curve, roc_auc_score, \ balanced_accuracy_score, accuracy_score class AverageMeter(object): """Computes and stores the average a...
4,314
1,441
import json import unittest from nose.tools import * from app import app def check_valid_json(res): eq_(res.headers['Content-Type'], 'application/json') content = json.loads(res.data) return content class AppTests(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app...
2,226
758
from ._version import __version__ # TODO: refactor the whole semester shit to semester configs
96
27
"""(Extremely) low-level import machinery bits as used by importlib and imp.""" class __loader__(object):pass def _fix_co_filename(*args,**kw): raise NotImplementedError("%s:not implemented" % ('_imp.py:_fix_co_filename')) def acquire_lock(*args,**kw): """acquire_lock() -> None Acquires the interpreter's...
2,013
647
from toolset.benchmark.test_types.framework_test_type import FrameworkTestType class DatarateTestType(FrameworkTestType): def __init__(self, config): kwargs = { 'name': 'datarate' } FrameworkTestType.__init__(self, config, **kwargs) def get_script_name(self): retur...
719
208
import unittest import time from multiprocessing import Process import os import psutil import requests import pandas from pyspark_gateway import server from pyspark_gateway import PysparkGateway class PysparkGatewayTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.server = Process(t...
2,150
700
from flask import jsonify import connexion from app import forms, models, InvalidUsage from services import common def all(): """ json response of available interviewers :return: """ url_params = connexion.request.args page = url_params.get('page', 0) limit = url_params.get('limit', 20)...
2,705
867
import pickle import os.path import sys, getopt from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import html from collections import namedtuple from dataclasses import dataclass from typing import List from rdf_serial...
20,549
6,303
import re import setuptools def get_version(path="src/ww/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1) def get_requirement...
2,242
721
class ScoringException(Exception): pass
44
12
# largest number a = int(input("Enter The First Number : ")) b = int(input("Enter The Seceond Number : ")) c = int(input("Enter The Thard Number : ")) Max = max(a, b, c) print("Largest Number Is :", Max) print('################## Seceond Program #################################') if a >= b and a >= c: ...
462
165
import typing import pydantic from sb_json_tools import jsondiff from karp.domain import model from karp.utility import unique_id from karp import errors as karp_errors from . import context # pylint: disable=unsubscriptable-object def get_by_id( resource_id: str, entry_uuid: unique_id.UniqueId, ctx: context....
7,144
2,340
expected_output = { 'inventory_item_index': { 0: { 'description': 'nexus7000 c7009 (9 slot) chassis ', 'name': 'chassis', 'pid': 'N7K-C7009', 'sn': 'JAF1704ARQG', 'vid': 'V01', }, 1: { 'description': 'supervisor module-2...
1,517
598
from __future__ import print_function import base64 from email.mime.text import MIMEText import os import pickle from time import sleep # project specific imports from utils import getTime, set_params, exitWithError from colors import printGreen, printFail import messageutils from inboxmanager import InboxManager # goo...
7,907
2,124
#### tensorboard使用 import atexit import os import os.path as osp import signal import time import torch import torchvision from tensorboardX import SummaryWriter import subprocess import sys import socket def get_host_ip(): """ 查询本机ip地址 :return: """ try: s=socket.socket(socket.AF_INET,soc...
2,155
882
import torch import math import time import csv from torch.autograd import Variable import torch.nn as nn from torch.nn import parameter import torch.nn.functional as F from torch.multiprocessing import Pool, Process, set_start_method, Lock, cpu_count import sys, os import numpy as np from copy import copy, deepcopy f...
17,731
4,891
# 9. Write a Python program to get a string which is n (non-negative integer) copies of a given string str = input('Enter any String value: ') num = int(input('Enter the number of copies you want of the string: ')) final = '' for i in range(num): final = final + str print(final)
299
96
from typing import Iterable import pytest from dagger.dsl.node_output_key_usage import NodeOutputKeyUsage from dagger.dsl.node_output_partition_usage import NodeOutputPartitionUsage from dagger.dsl.node_output_property_usage import NodeOutputPropertyUsage from dagger.dsl.node_output_reference import NodeOutputReferen...
4,005
1,146
import logging from jupyter_geppetto.service import PathService from .settings import template_path, home_page from .webapi import get class GeppettoController: @get('/geppettoprojects') def getProjects(self, **kwargs): # TODO still no project handling here. return {} @get(home_page) ...
581
158
import unittest import sys import ctypes import struct import binascii sys.path.append('.') from eth_scapy_someip import eth_scapy_someip as someip from eth_scapy_someip import eth_scapy_sd as sd class ut_someip_sd(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_00_SOMEIPSD(...
979
394
labels = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E'} A = np.array([ [0., 1., 0., 1., 0.], [0., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 0., 1., 0., 1.], [0., 0., 0., 0., 0.]]) print(f' A =\n {A}, \n A^T =\n {A.T}') print(f'labels: {labels}')
274
163
""" Given a string containing just the characters '(', ')', '{', '}', '[', ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty s...
1,087
342
import logging from itertools import chain, islice, repeat from typing import Callable, Iterator, TypeVar, Union #### setting up logger #### logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) T = TypeVar("T") def optional_object( argument: Union[None, T], object_factory: Callable[...,...
4,405
1,416
from typing import Iterator from itertools import chain from torchtext_th.data.token import Token class Sentence(object): def __init__(self, raw_sentence: str, delim: str = "|") -> None: self.delim = delim self.tokens = [] for t in raw_sentence.strip().split(delim): if len(t)...
782
270
#!/usr/bin/python # -*- coding: utf-8 -*- from .qt.QtCore import * from .qt.QtGui import * from .ftitlebar import FTitleBar from .fstatusbar import FStatusBar class FMainWindow(QMainWindow): sizeChanged = Signal() def __init__(self): super(FMainWindow, self).__init__() self._initFlags() ...
8,884
2,717