text
string
size
int64
token_count
int64
import math # return the delay of the specified path (= list of nodes) def path_delay(links, path): delay = 0 # go along nodes of the path and increment delay for each traversed link for i in range(len(path) - 1): # skip connections on same node without a link (both inst at same node) if path[i] != pa...
1,716
704
import os import csv import numpy as np import scipy.stats import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') def mean_confidence_interval(data, confidence=0.95): a = 1.0 * np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t.ppf((1 + confidence) / 2....
2,398
813
from __future__ import print_function import pandas as pd import numpy as np from sklearn.datasets import load_iris from skutil.preprocessing import * from skutil.preprocessing.balance import _BaseBalancer from numpy.testing import assert_array_equal from skutil.testing import assert_fails import warnings # Def data f...
4,844
1,804
#!/usr/bin/env python from Crypto.Cipher import AES from Crypto.Util.strxor import strxor from binascii import hexlify K = '0123456789abcdef' cipher = AES.new(K, AES.MODE_ECB) # Original Message M1 = K M2 = K Cm0 = cipher.encrypt('\0' * AES.block_size) Cm1 = cipher.encrypt(strxor(Cm0,M1)) Tm = Cm2 = cipher.encrypt(s...
754
374
import argparse 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.ArgumentTypeError('Boolean value expected.') class Options(): def __init__(self): """Reset t...
3,540
931
import json from companies_plugin import extractor from companies_plugin.utils import add_logger from scanr_doiresolver import LIB_PATH from scanr_doiresolver.resolver import resolve_publications @add_logger class Extractor(extractor.Extractor): def extract(self, headers, properties, message): """ ...
982
290
# -*- coding:utf-8 -*- # this is auto-generated by swagger-marshmallow-codegen from swagger_marshmallow_codegen.schema.legacy import ( AdditionalPropertiesSchema, LegacySchema ) from marshmallow import fields class Score(AdditionalPropertiesSchema): name = fields.String(required=True) class Meta: ...
361
113
import pytest import pandas as pd import numpy as np from os import stat from io import StringIO from epic.bigwig.create_bigwigs import _create_bigwig from epic.config.genomes import create_genome_size_dict @pytest.fixture def input_data(): contents = u"""Chromosome Bin End examples/test.bed chr1 887600 887799 ...
1,280
718
# MIPLearn: Extensible Framework for Learning-Enhanced Mixed-Integer Optimization # Copyright (C) 2020-2021, UChicago Argonne, LLC. All rights reserved. # Released under the modified BSD license. See COPYING.md for more details. from io import StringIO from miplearn.solvers import _RedirectOutput def test_redirec...
555
176
import math def Correlation(scores): physics = [] maths = [] chemistry = [] for each_scores in scores: values = each_scores.split("\t") maths.append(int(values[0])) physics.append(int(values[1])) chemistry.append(int(values[2])) length = len(physics) value1 = ...
1,717
758
import sys import unittest import configparser sys.path.append("./svc") class CIIneKoKo_DB(unittest.TestCase): def setUp(self): import iinekoko_db self.o_conf = configparser.ConfigParser() self.o_conf.read("./svc/config.ini") self.o_conn = iinekoko_db.CDatabase(self.o_conf) d...
2,617
1,008
# Class to store champion names in one location class Champion: """Champions in Paladins""" DAMAGES = ["Cassie", "Kinessa", "Drogoz", "Bomb King", "Viktor", "Sha Lin", "Tyra", "Willo", "Lian", "Strix", "Vivian", "Dredge", "Imani", "Tiberius"] FLANKS = ["Skye", "Buck", "Evie", "Androxus", "Mae...
987
376
import logging from typing import Optional, List, Any import gpuz.utility as utility from pathlib import Path import os import pandas as pd from pandas.core.frame import DataFrame import numpy as np import matplotlib as mp logger: logging.Logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class D...
2,292
735
from posix import listdir import requests from bs4 import BeautifulSoup as bs import math import sys, getopt import re import os def re_cleaner(target: str, rep: str) -> str: return re.sub("[^0-9a-zA-Z]+", rep, target) # For Oxford ============================================================================== ...
4,173
1,529
import os from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline # from rllab.envs.mujoco.gather.swimmer_gather_env import SwimmerGatherEnv os.environ["THEANO_FLAGS"] = "device=cpu" from rllab.envs.gym_env import GymEnv from rllab.envs.normalized_env import normalize from rllab.policies.gaussian_mlp...
6,319
2,177
""" This is to generate interaction energies and corresponding translational vectors, given a fixed receptor and an ensemble of ligand coordinates (including rotations and/or configurations) """ from __future__ import print_function import numpy as np import netCDF4 try: from bpmfwfft.grids import RecGrid fr...
17,257
5,847
import json import re from abc import ABC, abstractmethod from dataclasses import dataclass, field from os.path import splitext from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Type, Union from PIL import Image from ruamel.yaml import YAML from kotori.error import ConfigError __all__ = [...
6,241
1,890
import os import re from pprint import pprint from pandas.io.json import json_normalize import datetime import argparse import sys DATE = 'date' LEVEL = 'level' TYPE = 'type' CLASS = 'class' MESSAGE = 'message' def match_date(line): match_this = '' matched = re.match(r'\[\w\w\w\s\w\w\w \d\d \d\d:\d\d:\d\d\s\d...
4,587
1,323
from nimanifold.data.csv import * from nimanifold.data.sample import *
71
25
import sys import os import numpy as np import ast import pandas as pd from LEBondUpdater import bondUpdater import polychrom from polychrom.starting_conformations import grow_cubic from polychrom.hdf5_format import HDF5Reporter, list_URIs, load_URI, load_hdf5_file from polychrom.simulation import Simulation from pol...
452
144
from PySide2.QtCore import Signal from PySide2.QtWidgets import QWidget from deca.db_view import VfsView class IVfsViewSrc(QWidget): signal_visible_changed = Signal(VfsView) signal_selection_changed = Signal(VfsView) def vfs_get(self): return None def vfs_view_get(self): return None ...
373
126
""" Computes the probability field of beached particles from Ocean Parcels simulations. Computes the posterior probability in the latitude of the beached particles. """ import numpy as np import xarray as xr import pandas as pd import os def time_averaging_coast(array, window=30): """It averages the counts_americ...
7,746
2,428
import math import torch import torch.nn as nn import torch.nn.functional as F from models.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d from models.aspp import build_aspp from models.decoder import build_decoder import pdb class AttentionDecoder(nn.Module): def __init__(self, num_classes, modal_num, bac...
2,985
1,135
import scipy as sp from pyssp.util import ( get_frame, add_signal, compute_avgpowerspectrum ) def writeWav(param, signal, filename): import wave with wave.open(filename, 'wb') as wf: wf.setparams(param) s = sp.int16(signal * 32767.0).tostring() wf.writeframes(s) def jointMap(sign...
2,505
926
''' harmalysis - a language for harmonic analysis and roman numerals Copyright (C) 2020 Nestor Napoles Lopez 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 3 of t...
4,940
2,080
import hashlib from Crypto.Cipher import AES class Crypto: SALT = "@uhooinc.com" def __init__(self, clientCode): self.key = hashlib.md5( clientCode.encode("utf-8") ).digest() # initialization key self.length = AES.block_size # Initialize the block size self.aes =...
1,335
423
############################################################################## # Institute for the Design of Advanced Energy Systems Process Systems # Engineering Framework (IDAES PSE Framework) Copyright (c) 2018-2019, by the # software owners: The Regents of the University of California, through # Lawrence Berkeley N...
8,350
2,608
# Generated by Django 3.1.3 on 2020-11-23 15:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('scheduler', '0007_fetchintention_one_to_one_attempt'), ] operations = [ migrations.AddField( mo...
1,642
457
import unittest import gym import numpy as np from connect_four.hashing import TicTacToeHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable class TestSQLiteTranspositionTable(unittest.TestCase): def setUp(self) -> None: self.env = gym.make('tic_tac_toe-v0') ...
2,555
884
from nipype import config config.enable_debug_mode() from banana.testing import BaseTestCase as TestCase # @IgnorePep8 @Reimport # from banana.study.multimodal.test_motion_detection import ( # @IgnorePep8 @Reimport # MotionDetection, inputs) from banana.study.multimodal.mrpet import create_motion_correction_class...
1,226
454
# # (C) dGB Beheer B.V.; (LICENSE) http://opendtect.org/OpendTect_license.txt # AUTHOR : Bert # DATE : August 2018 # # Module init # __version__ = '1.0.0'
162
80
""" Test module for the Fedex CountryService WSDL. """ import unittest import logging import sys sys.path.insert(0, '..') from fedex.services.country_service import FedexValidatePostalRequest # Common global config object for testing. from tests.common import get_fedex_config CONFIG_OBJ = get_fedex_config() loggin...
1,052
337
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab from __future__ import unicode_literals, division, absolute_import, print_function import os import sys import shutil import inspect import glob import zipfile import pythonpatch if sys.version_info >= (3,): import url...
3,730
1,340
import struct from pymoku import _frame_instrument _OSC_SCREEN_WIDTH = 1024 class VoltsData(_frame_instrument.InstrumentData): """ Object representing a frame of dual-channel data in units of Volts, and time in units of seconds. This is the native output format of the :any:`Oscilloscope` instrument....
5,696
1,819
import os from PIL import ImageGrab import time import win32api, win32con from PIL import ImageOps from numpy import * import pyautogui import random from ctypes import windll user32 = windll.user32 user32.SetProcessDPIAware() #some sort of DPS problem unrelated to project #this stops the images from be...
6,205
2,239
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class ConvLSTMCell(nn.Module): """ Generate a convolutional LSTM cell Adapted from "RVOS: End-to-End Recurrent Network for Video Object Segmentation" """ def __init__(self, input_size, hidden_size...
6,047
2,144
import logging from logging.config import fileConfig import os, os.path import imageRecognition #Test Folder TestFolder = 'WorkingFolder/TestImages/' # Create the Working folders working_folders = ['logs','.metadata','WorkingFolder','./Workingfolder/OutputImages'] [os.makedirs(folder) for folder in working_folders...
907
280
total = 0 media = 0 hmais = 0 no = '' contm = 0 from datetime import date atual = date.today().year for p in range(1,5): print('{}° Pessoa'.format(p)) nome = str(input('Nome: ')).strip().capitalize() ns = int(input('O ano em que nasceu: ')) sexo = str(input('Sexo: ')).strip().upper() idade = atual ...
755
292
''' The CDP module contains all the tools required to simulate a collateralized debt position, such as increasing or decreasing its leverage (boost and repay), closing the vault to calculate its lifetime profit, adding collateral or drawing more debt. The position is represented as an object whose methods provide a...
9,575
2,760
# -*- coding: utf-8 -*- from functools import partial from nose.tools import assert_equal, assert_in, assert_less, assert_raises, \ with_setup, assert_true from nose.tools import assert_false from clustertools import ParameterSet, Result, Experiment from clustertools.state import RunningState, CompletedState, Abo...
5,683
1,833
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs def find_words(words): split_words={} count_all = 0 unused_words = u" \t\r\n,。:;、“‘”【】『』|=+-——()*&……%¥#@!~·《》?/?<>,.;:'\"[]{}_)(^$!`" unused_english = u"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" for i in u...
1,657
689
#Embedded file name: ACEStream\Plugin\EngineWx.pyo import os import sys from traceback import print_exc try: import wxversion wxversion.select('2.8') except: pass try: import wx except: print 'wx is not installed' os._exit(1) import ACEStream from ACEStream.GlobalConfig import globalConfig fro...
2,971
1,024
from tcp_statemachine import TCPStateMachine, Data import socket class Client: """ Client class """ def __init__(self, statemachine, data): self.ME = 'client' self.HOST = '127.0.0.1' self.PORT = 22085 self.ADDRESS = (self.HOST, self.PORT) self.client_socket = socket.socket() def run(sel...
899
329
# https://www.hackerrank.com/challenges/minimum-swaps-2 # Complete the minimumSwaps function below. def minimumSwaps(arr): steps = 0 # for i, a in enumerate(arr): for i in range(len(arr)): while arr[i] != i+1: #arr = [a if x == i+1 else x for x in arr] #print(arr) ...
467
158
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
3,081
941
msg = "Hello World, i'm coming for you" print(msg)
51
20
from onegov.user.auth.clients.kerberos import KerberosClient from onegov.user.auth.clients.ldap import LDAPClient __all__ = ('KerberosClient', 'LDAPClient')
158
58
import glob import os def images_in_dir(images_dir, file_types=('*.png', '*.jpg', '*.jpeg', '*.gif')): """ :param images_dir: directory that contains target images :param file_types: image files extend :return: full image file path list """ file_names = [] for ext in file_types: fi...
746
248
''' Created on Oct 8, 2013 @author: akittredge ''' import dateutil.parser import xmltodict from financial_fundamentals.exceptions import ValueNotInFilingDocument class XBRLMetricParams(object): '''Bundle the parameters sufficient to extract a metric from an xbrl document. ''' def __init__(self, poss...
4,931
1,480
# Licensed under the BSD 3-Clause License # Copyright (C) 2021 GeospaceLab (geospacelab) # Author: Lei Cai, Space Physics and Astronomy, University of Oulu __author__ = "Lei Cai" __copyright__ = "Copyright 2021, GeospaceLab" __license__ = "BSD-3-Clause License" __email__ = "lei.cai@oulu.fi" __docformat__ = "reStructur...
6,235
2,348
from infra.usuario_dao import \ listar as dao_listar, \ consultar as dao_consultar, \ cadastrar as dao_cadastrar, \ alterar as dao_alterar, \ remover as dao_remover,\ loadUserEmail as dao_loadUserEmail,\ validarLogin as dao_validarLogin,\ validaMatriculaUsuario as dao_validaMatriculaUsua...
914
361
from rest_framework import permissions class IsMemberOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to access (read/write) """ def has_permission(self, request, view): return request.user.is_authenticated def has_object_permission(self, request,...
421
117
import random import torch import numpy as np # 设置随机种子,一旦固定种子,后面依次生成的随机数其实都是固定的 def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # 计算评价指标:准确率,召回率,F1值 def calculate(data): p = -1 r = -1 f1 = -1 if data[0] > 0: p = data[2] / data[0]...
473
270
# Generated by Django 3.1.2 on 2021-05-21 06:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('budget', '0003_auto_20210521_1252'), ] operations = [ migrations.AlterField( model_name='expense', name='tags', ...
769
254
from ._load_hetrec import load_hetrec_to_df from ._df2ffm import DF2FFMConverter from ._utils import load_ffm, save_ffm, load_pickle, save_pickle
146
58
# -*- coding: utf-8 -*- """ Created on Tue Dec 13 23:10:40 2016 @author: zhouyu """ #%% import pandas as pd import numpy as np import os import re import nltk from nltk.corpus import stopwords from bs4 import BeautifulSoup os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing') #%% step1: impor...
7,689
2,732
import unittest from stl.types import * class TestTypes(unittest.TestCase): def test_facet_geometry(self): facet = Facet( (1, 0, 0), [ (0, 0, 0), (1, 0, 0), (0, 1, 0), ], ) self.assertEqual(facet.a, 1.0) ...
1,210
430
from ..common.exceptions import DoesNotExist class DatasetDoesNotExist(DoesNotExist): entity_name = "Dataset"
116
39
import PySimpleGUI as sg """ PySimpleGUI The Complete Course Lesson 7 Multiple Independent Windows """ # Design pattern 2 - First window remains active layout = [[ sg.Text('Window 1'),], [sg.Input()], [sg.Text('', size=(20,1), key='-OUTPUT-')], [sg.Button('Launch 2'), sg.Butt...
967
332
#!/usr/bin/python import os import sys import StringIO import argparse import json import zipfile from PIL import Image, ImageColor import xml.etree.cElementTree as ET # TODO: compose multiple layers def compose_image(indexes, archive): file = 'layer' + str(indexes[0]) + '.png' return Image.open(StringIO.StringIO(...
6,277
2,750
from django.contrib import admin from calls.onsets.models import Recording class RecordingAdmin(admin.ModelAdmin): list_display = ('audio', 'image', 'length') admin.site.register(Recording, RecordingAdmin)
212
61
""" Your secrets and configurations items you must rename this file secrets.py and customize as needed """ # Wifi settings SSID = "mywifi" PASSWD = "thesecretpassword" # Network - comment to use DHCP (but slighly slower) IPADDR = "192.168.0.100" MASK = "255.255.255.0" GW = "192.168.0.1" DNS = "1.1.1.1" # MQTT s...
505
240
# 练习1:在屏幕上显示跑马灯文字 from random import randint import os import time def marquee(): content = "我很开心。。。" while True: os.system("clear") print(content) time.sleep(.2) content = content[1:]+content[0] # marquee() # 练习2:设计一个函数产生指定长度的验证码,验证码由大小写字母和数字构成 def genrentae_code(l=4):...
2,000
1,039
# -*- coding: utf-8 -*- def get_client_ip_address(request): """ Get the client IP Address. """ return request.META['REMOTE_ADDR']
147
57
# DExTer : Debugging Experience Tester # ~~~~~~ ~ ~~ ~ ~~ # # Copyright (c) 2019 by SN Systems Ltd., Sony Interactive Entertainment Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # ...
2,117
663
import inspect import pytest from bottery.platform import BaseEngine def test_baseengine_platform_name_not_implemented(): """Check if attributes from the public API raise NotImplementedError""" engine = BaseEngine() with pytest.raises(NotImplementedError): getattr(engine, 'platform') @pytest.m...
1,825
561
""" Module handling the potential class. """ from copy import deepcopy from fmm3dpy import hfmm3d, lfmm3d from numpy import array, ndarray, pi, sqrt, tanh from warnings import warn from ..utilities.exceptions import AlgorithmWarning from ..utilities.fdints import fdm1h, invfd1h from .force_pm import force_optimized_gr...
26,071
8,411
from fastapi import APIRouter router = APIRouter() @router.get("/api") async def api(): """Discoverable API by hitting root endpoint""" return { "links": { "datasets": "/datasets", "natural_earth_feature": "/natural_earth_feature", "viewport": "/viewport" ...
328
98
import re import pytest from lupin.errors import InvalidMatch from lupin.validators import Match @pytest.fixture def validator(): regexp = re.compile("hello") return Match(regexp) class TestCall(object): def test_raise_error_if_does_not_match(self, validator): with pytest.raises(InvalidMatch) ...
593
195
#!/usr/bin/env python spacing = 0.1 # m lines = [] for c in range(0, 8): rs = [range(11), reversed(range(11))][c % 2] for r in rs: lines.append(' {"point": [%.2f, %.2f, %.2f]}' % (c*spacing, 0, (r)*spacing)) print '[\n' + ',\n'.join(lines) + '\n]'
289
131
'''There is an objective test result such as “OOXXOXXOOO”. An ‘O’ means a correct answer of a problem and an ‘X’ means a wrong answer. The score of each problem of this test is calculated by itself and its just previous consecutive ‘O’s only when the answer is correct. For example, the score of the 10th problem is 3 t...
1,237
374
# -*- coding: utf-8 -*- from app import celery, app @celery.task() def add_together(a, b): app.logger.info('hello world') return a + b # from common.extensions import celery # from flask import current_app # # # @celery.task() # def add_together(a, b): # current_app.logger.info('hello world') # retur...
328
122
# -*- coding: utf-8 -*- """3_Linear_regression_on_pixels.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1nhECM9OxwIw8BjEqsQcSUwojX2KYrh1I """ from google.colab import drive #to retrieve data from drive drive.mount('/content/drive/') cd 'driv...
11,411
3,679
import functools import ci.util ctx = ci.util.ctx() @functools.lru_cache() def cfg_factory(): return ctx.cfg_factory()
127
51
""" Create 10km x 10km grid using the country shapefile. Written by Ed Oughton. Winter 2020 """ import argparse import os import configparser import geopandas as gpd from shapely.geometry import Polygon, mapping import pandas as pd import numpy as np import rasterio from rasterstats import zonal_stats BASE_DIR = '....
2,459
923
#!/usr/bin/env python import unittest test_modules = [ 'test.test_config', 'test.test_secrets', 'test.test_spotify', 'test.test_youtube' ] if __name__ == "__main__": suite = unittest.TestSuite() for tm in test_modules: suite.addTest(unittest.defaultTestLoader.loadTestsFromName(tm)) ...
366
132
import os import tempfile from time import time import numpy as np import sounddevice as sd from PySide2.QtWidgets import QApplication, QFileDialog from scipy.io.wavfile import write # Config t = 3 # s fs = 44100 def save(x, fs): # You have to create a QApp in order to use a # Widget (QFileDialg) app =...
1,281
474
#!/usr/bin/python import sys sys.path.append('./') import unittest import copy import numpy as np from hybmc.mathutils.Helpers import BlackImpliedVol, BlackVega from hybmc.termstructures.YieldCurve import YieldCurve from hybmc.models.AssetModel import AssetModel from hybmc.models.HybridModel import HybridModel from...
10,977
4,522
from .distributed import * from .model import * from .sentiment_classifier import * from .transformer import * from .transformer_utils import *
143
39
import socket class peer: __db = None __s = socket __protocol = '' __port = 5060 __s_address = () __buff_size = 4096 def __init__(self, protocol='TCP', port=5060, buff_size=4096): self.__set_protocol(protocol) self.__set_port(port) self.__set_buff_size(buff_size)...
2,927
908
#!/usr/bin/env python ''' Copyright (c) 2019-2020, Juan Miguel Jimeno All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, thi...
3,387
1,171
# Copyright 2014 Isotoma Limited # # 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,909
1,150
# from type.models import User, Requirement, Involvement, Competition, Text
77
24
""" entradas cantidadchelinesaustriacos-->c-->float cantidaddragmasgriegos-->dg-->float cantidadpesetas-->p-->float salidas chelines_a_pesetas-->c_p-->float dragmas_a_francosfrancese-->dg_ff-->float pesetas_a_dolares-->p_d-->float pesetas_a_lirasitalianas-->p_li-->float """ #entradas c=float(input("Ingrese la cantida...
793
363
#importing necessary libraries import numpy as np import pandas as pd import string import streamlit as st header = st.container() dataset = st.container() fearure = st.container() model_training = st.container() def get_data(file_name): df = pd.read_csv(file_name , header = None) return df with header: ...
4,453
1,525
#!/usr/bin/env python # -*- coding:utf-8 -*- SECRET_KEY = 'some secret key' TEMPLATES_AUTO_RELOAD = True PROJECT_NAME = 'SpiderManage' # Redis Config REDIS_HOST = '120.25.227.8' REDIS_PORT = 6379 REDIS_PASSWORD = 'xuxinredis' # SQLite # SQLALCHEMY_DATABASE_URI = 'sqlite:///C:/Users/sheep3/workplace/SpiderManage/data.d...
540
261
from PyPrometheusQueryClient import PrometheusQueryClient import json from pathlib import Path from datetime import datetime class Prometheus: def __init__(self, url, metrics_config_file=None, cache_path=None, cache_ttl=3600, ssl_verify=True, starttime=None, endtime=None): self._metrics_config_file = met...
3,989
1,181
import pytest import os import json import jsonschema from ruamel.yaml import YAML def test(): def extract_snippets(): start = 0 end = len(markdown) while start < end: snippet_start = markdown.find("```yaml\n", start, end) if snippet_start == -1: br...
5,557
1,402
import vkrpg class MainContext(vkrpg.contexts.BaseContext): def on_message(self, msg): vkrpg.chat.send(msg['peer_id'], text='Привет, VKID#{}!'.format(msg['from_id']))
188
72
import secrets from flask import Flask , render_template , url_for , send_from_directory from flaskprediction import app from flaskprediction.utils.predict import Predictor from flaskprediction.forms import CarDetailsForm , TitanicDetailsForm , BostonDetailsForm , HeightDetailsForm, CatImageForm from PIL import Imag...
4,613
1,452
import requests import re from time import sleep from datetime import datetime import shutil import elasticsearch2 from elasticsearch_dsl import Search, Q from collections import OrderedDict from sqlalchemy import create_engine from subprocess import Popen, PIPE, STDOUT import shlex import glob import csv # from api...
14,349
4,151
import enum import re import lxml.html from typing import Any, Dict, List, Union, Optional from typing import TYPE_CHECKING if TYPE_CHECKING: from .atserver import AternosServer class ServerOpts(enum.Enum): """server.options file""" players = 'max-players' gm = 'gamemode' difficulty = 'difficult...
8,180
3,458
from __future__ import print_function import unittest import numpy as np from openmdao.api import Problem, Group, pyOptSparseDriver, DirectSolver, SqliteRecorder from dymos import Phase from dymos.utils.indexing import get_src_indices_by_row from dymos.phases.components import ControlInterpComp from CADRE.odes_dym...
11,859
4,911
from deso.utils import getUserJWT import requests class Media: def __init__(self, publicKey=None, seedHex=None, nodeURL="https://node.deso.org/api/v0/"): self.SEED_HEX = seedHex self.PUBLIC_KEY = publicKey self.NODE_URL = nodeURL def uploadImage(self, fileList): #uploads imag...
959
290
# This file is executed on every boot (including wake-boot from deepsleep) import esp esp.osdebug(None) import wifi wifi.connect(repl=False) import gc gc.collect()
169
61
import pytest from app.models import AVScanResult @pytest.fixture def _scan_result() -> AVScanResult: clean = 10 virus = 0 skipped = 0 return AVScanResult(clean, virus, skipped) def test_avscanresult_init(_scan_result): result = AVScanResult(10, 0, 0) assert result == _scan_result def test...
1,790
661
# -*- coding: utf-8 -*- """Activate virtualenv for current interpreter: Source: https://github.com/pypa/virtualenv Use exec(open(this_file).read(), {'__file__': this_file}). """ import os import site import sys try: abs_file = os.path.abspath(__file__) except NameError: raise AssertionError( "You must...
1,424
515
from sqlalchemy import create_engine from sqlalchemy import ( Table, Column, Integer, String, Text, Boolean, ForeignKey, Enum, DateTime ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref, sessionmaker Session = sessionmaker() Model = declarative_base() ...
2,731
826
from keychain import Keychain
30
8
# PYTHON STANDARD LIBRARY IMPORTS --------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import deque from collections import OrderedDict from math import radians from math import pi from operator import...
152,955
37,330