id
stringlengths
3
8
content
stringlengths
100
981k
3319873
import os import logging from abc import ABCMeta, abstractmethod import numpy as np from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import pandas as pd import h5py from specutils import Spectrum1D from astropy import units as u logger = logging.getLogger(__name__) class BaseSpectralGr...
3319919
async def test3(): async for i in x: if i > 20: continue else: c d
3320008
def f(n): return (n-1)/5*4 #print f(96.) def f6(n): for i in range(6): n=f(n) return n def is_int(n): return abs(n - int(n)) < 0.0000001 n=0 found = False while not found: n +=1 found = is_int(f6(float(n))) print n print 12495/5
3320017
import logging import os from google.appengine.ext.webapp import template from controllers.base_controller import LoggedInHandler from models.sitevar import Sitevar class AdminGamedayDashboard(LoggedInHandler): """ Configure things about gameday """ def get(self): self._require_admin() ...
3320032
from .model import Model class ConditionalModel(Model): """ A conditional maximum-entropy (exponential-form) model p(x|w) on a discrete sample space. This is useful for classification problems: given the context w, what is the probability of each class x? The form of such a model is:: ...
3320043
from collections import deque from math import inf from typing import List, Union, Deque from hwt.code import Concat from hwt.hdl.types.bits import Bits from hwt.hdl.types.bitsVal import BitsVal from hwt.hdl.types.hdlType import HdlType from hwt.hdl.value import HValue from hwt.synthesizer.rtlLevel.constants import NO...
3320068
import testflows.settings as settings from testflows.core import * @TestStep(Given) def instrument_clickhouse_server_log(self, node=None, test=None, clickhouse_server_log="/var/log/clickhouse-server/clickhouse-server.log"): """Instrument clickhouse-server.log for the current test (default) by adding st...
3320078
import configparser import time from TM1py import TM1Service config = configparser.ConfigParser() # storing the credentials in a file is not recommended for purposes other than testing. # it's better to setup CAM with SSO or use keyring to store credentials in the windows credential manager. Sample: # Samples/credent...
3320097
from leapp.utils.deprecation import deprecated @deprecated('2010-01-01', 'Deprecated class without __init__') class DeprecatedNoInit(object): pass @deprecated('2010-01-01', 'Deprecated class with __init__') class DeprecatedWithInit(object): pass @deprecated('2010-01-01', 'Deprecated base class without __i...
3320139
import cv2 import sys, datetime from time import sleep import numpy as np GREEN = (0, 255, 0) BLUE = (255, 0, 0) RED = (0, 0, 255) def draw_boxes(frame, boxes, color=(0,255,0)): for (x, y, w, h) in boxes: cv2.rectangle(frame, (int(x), int(y)), (int(x+w), int(y+h)), color, 2) return frame def resize_...
3320176
import time import copy import torch import torch.nn as nn from collections import defaultdict import numpy as np import torch import math import torch.nn.functional as F from torch.nn import Sequential from torch.nn import init from torch.nn.parameter import Parameter ### from DIM.dim_loss import * from DIM.train_pr...
3320211
MIN_LATITUDE = -90.0 MAX_LATITUDE = 90.0 MIN_LONGITUDE = -180.0 MAX_LONGITUDE = 180.0 CACHE_DIR = "cache"
3320223
import tempfile import platform import subprocess from sys import version_info from pathlib import Path from pkgutil import iter_modules from skbuild import setup # To be replaced by: from setuptools_scm import get_version def get_version(): return "2.3.0" def _zivid_sdk_version(): return "2.5.0" def _zivi...
3320249
import plugins.adversary.app.config as config from plugins.adversary.app.commands import static from plugins.adversary.app.operation.operation import Step, OPRat, OPFile, OPPersistence class LogonPersistence(Step): """ Description: This step attempts to maintain persistence using script configured to ...
3320259
import copy from collections import defaultdict from typing import List, Dict, Any, Union, Generator from paramtools.sorted_key_list import SortedKeyList from paramtools.typing import ValueObject def default_cmp_func(x): return x class ValueItem: """ Handles index-based look-ups on the Values class. ...
3320288
from optparse import OptionValueError from twitter.common.lang import Compatibility from twitter.common.quantity import Data, Time, Amount class InvalidTime(ValueError): def __init__(self, timestring): ValueError.__init__(self, "Invalid time span: %s" % timestring) def parse_time(timestring): """ Parse...
3320307
import logging import os import math from collections import defaultdict from gensim import corpora # 引入斷詞與停用詞的配置 from Matcher.matcher import Matcher class Evaluator(Matcher): """ 讀入一串推文串列,計算出當中可靠度最高的推文 """ def __init__(self,segLib="jieba"): #FIXME 若「線上版本」受記憶體容量限制,需考慮更換為 jieba! supe...
3320317
import abunSplitter from finisherSCCoreLib import houseKeeper import time import argparse import abunHouseKeeper t0 = time.time() parser = argparse.ArgumentParser(description='aSplitter') parser.add_argument('folderName') parser.add_argument('mummerLink') parser.add_argument('-f', '--fast', help= 'Fast aligns conti...
3320367
from .models import make, load from . import convnet4 from . import resnet12 from . import resnet from . import classifier from . import meta_baseline
3320373
import dedupe import logging import os import re import sys import traceback from collections import defaultdict from datetime import datetime from django.conf import settings from django.contrib.postgres.search import TrigramSimilarity from django.db import transaction from django.db.models import Q, Max from unideco...
3320374
from triggerflow import Triggerflow, CloudEvent from triggerflow.eventsources import RedisEventSource from triggerflow.functions import PythonCallable redis_config = { 'host': '127.0.0.1', 'port': 6379, 'db': 0, 'password': '<PASSWORD>' } redis_eventsource = RedisEventSource(**redis_config) tf = Trig...
3320391
def is_palindrome(n): n = str(n) return n == n[::-1] def main(): max = 0 for i in range(999, 99, -1): for j in range(999, 99, -1): if is_palindrome(i*j): if i*j>max: max = i*j print(max) if __name__ == '__main__': main()
3320448
from PIL import Image from PIL import ImageFilter import utils.logger as logger #from utils.rotate import rotate from config import * from typing import Tuple, List import sys i = 0 def crop_image(image, area:Tuple) -> object: ''' Uses PIL to crop an image, given its area. Input: image - PIL opened image Area - C...
3320479
import unittest import sys sys.path.append('../') from Phyme import rhymeUtils as ru from Phyme.util import flatten class RhymeUtilsTest(unittest.TestCase): def test_get_phones(self): # get_phones returns correct (number of) phones self.assertEqual(len(ru.get_phones('dog')), 3) self.asser...
3320484
import argparse def get_args(): parser = argparse.ArgumentParser( description="GNN baselines on ogbgmol* data with Pytorch Geometrics" ) parser.add_argument( "--device", type=int, default=0, help="which gpu to use if any (default: 0)" ) parser.add_argument( "--gnn", ...
3320510
import numpy import matplotlib.pyplot as plt import pandas import math from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error import pandas as pd import scipy.io as sio from os import listdir from os...
3320544
from pynwb import TimeSeries import numpy as np from bisect import bisect, bisect_left def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray: """ For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be generated. Parameters ...
3320566
import pytest from sonata.circuit import File, Edge def test_edge_population(net): edges = net.edges['v1_to_v1'] assert(len(edges) == 48286) assert(edges.source_population == 'v1') assert(edges.target_population == 'v1') def test_population_itr_all(net): edges = net.edges['v1_to_v1'] for i,...
3320619
import sys, wx sys.path.append('../../') from sciwx.mesh import Canvas3D, MCanvas3D from sciapp.util import surfutil, meshutil from sciapp.object import Scene, Mesh, Surface2d, Surface3d, TextSet, Volume3d from sciwx.mesh import Canvas3DFrame, Canvas3DNoteBook, Canvas3DNoteFrame import sys, wx import scipy.ndimage as ...
3320644
from solvers import MCH,MPF,Pseudo,ClusterExpansion,Enumerate,RegularizedMeanField from utils import *
3320646
class Orcamento: def __init__(self, valor): self.__valor = valor @property def valor(self): return self.__valor
3320669
r""" Tests for the :mod:`scglue.metrics` module """ # pylint: disable=redefined-outer-name, wildcard-import, unused-wildcard-import import numpy as np import pytest import scglue.metrics from .fixtures import * def test_mean_average_precision(rna_pp): mean_average_precision = scglue.metrics.mean_average_prec...
3320677
from datasets.census_dataloader import get_income_census_dataloaders from models.experiment_adaptation_pretrain_learner import FederatedDAANLearner from models.experiment_finetune_target_learner import FederatedTargetLearner from utils import get_timestamp, get_current_date, create_id_from_hyperparameters, test_classif...
3320720
import os import sys import hashlib from urllib.request import urlopen from math import ceil from loguru import logger from tqdm import tqdm from nltk.internals import is_writable path_list = [] _paths_from_env = os.environ.get("TPS_DATA", str("")).split(os.pathsep) path_list += [d for d in _paths_from_env if d] i...
3320740
import glob import user_paths as up import os import pandas as pd def build(): # folder name, map name, interpreter file name otypes = [ ('nD', 'nDMaterials', 'OpenSeesNDMaterialCommands', 'Material',), ('uniaxial', 'uniaxialMaterials', 'OpenSeesUniaxialMaterialCommands', 'Material'), ...
3320771
from operator import itemgetter class ColorsForCounts(object): """ Maintain a collection of count thresholds and colors with methods to get a color or a CSS name for a count. @param colors: An C{iterable} of space separated "value color" strings, such as ["100 red", "200 rgb(23, 190, 207)", "...
3320774
from sqlite3 import connect database_name = 'database.db' class DataBase: @staticmethod def createTable(query): try: con = connect(database_name) c = con.cursor() c.execute(query) except Exception as e: print("error:", e) @staticmethod...
3320790
import pytest from mkdocs_redirects.plugin import get_relative_html_path @pytest.mark.parametrize(["old_page", "new_page", "expected"], [ ("old.md", "index.md", "../"), ("old.md", "new.md", "../new/"), ("foo/old.md", "foo/new.md", "../new/"), ("foo/fizz/old.md", "foo/bar/new.md", "../../bar/new/"), ...
3320794
import platform from .exceptions import InvalidInputType from .flags import Flags LINUX = 'Linux' WINDOWS = 'Windows' OSX = 'Darwin' # For format() and format_input() default_end = '\n' class Printy: """ Applies a format to the output of the print statement according to the flag (or flags). We can...
3320866
from __future__ import absolute_import, print_function import unittest import torch import random import time from lib.models import AlexNetV1, AlexNetV2 class TestAlexNet(unittest.TestCase): def setUp(self): self.x = torch.randn((2, 3, 224, 224)) def tearDown(self): pass def test_ale...
3320869
from .DyTrader import * class UiTrader(DyTrader): """ 券商窗口交易接口基类 """ name = 'UI' heartBeatTimer = 60 pollingCurEntrustTimer = 5 maxRetryNbr = 3 # 最大重试次数 def __init__(self, eventEngine, info, accountConfigFile=None): super().__init__(eventEngine, info, None, accountConfig...
3320876
from collections import OrderedDict from pathlib import Path import pytest from Pegasus.yaml import dumps, loads @pytest.mark.parametrize( "s, expected", [ ("key: 1", 1), ("key: 2018-10-10", "2018-10-10"), ("key: yes", "yes"), ("key: true", True), ], ) def test_loads(s, e...
3320954
from .point2d import Point2d from .point3d import Point3d from .intervals import Interval, Scale """ increase to encompass a point increase/decrease by a margin addition between two boxes boolean operations? two corner points initialized with: intervals interval tuples width/height/depth points arb...
3320979
import os import pickle import shutil import tempfile import unittest from typing import Any, Dict, List import web3 from web3.main import Web3 from moonworm.contracts import ERC20 from moonworm.crawler.function_call_crawler import ( EthereumStateProvider, FunctionCallCrawler, PickleFileState, Web3Sta...
3320991
import json import os import pybullet as p from bddl.object_taxonomy import ObjectTaxonomy from IPython import embed def set_pos_orn(body_id, pos, orn): p.resetBasePositionAndOrientation(body_id, pos, orn) def get_pos_orn(body_id): return p.getBasePositionAndOrientation(body_id) def save_box(obj_inst_dir...
3321007
import torch import urllib import matplotlib.pyplot as plt import os model = torch.hub.load('pytorch/vision:v0.9.0', 'deeplabv3_resnet101', pretrained=True) model.eval() # Download an example image from the pytorch website url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg"...
3321009
import pandas as pd import numpy as np from gensim.models import KeyedVectors from sklearn.manifold import TSNE import matplotlib.pyplot as plt # http://www.fao.org/countryprofiles/iso3list/en/ country = pd.read_table('ch07/countries.tsv') country = country['Short name'].values model = KeyedVectors.load_word2vec_for...
3321011
import os import shutil import torch # refer to https://github.com/xternalz/WideResNet-pytorch def save_checkpoint(state, config, is_best, filename='checkpoint.pth.tar'): """Saves checkpoint to disk""" if not os.path.exists(config.snapshot_dir): os.makedirs(config.snapshot_dir) filename = config....
3321086
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.vince111b import vince111b def test_vince111b(): """Test module vince111b.py by downloading vince111b.csv and testing shape of extracted d...
3321087
from aiogithub import objects from aiogithub.objects.response import BaseResponseObject from aiogithub.utils import return_key class Commit(BaseResponseObject): _url = 'repos/{login}/{repo}/commits/{sha}' @staticmethod def _get_key_mappings(): return { 'author': objects.User, ...
3321096
import math import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageFilter from skimage import io, measure from scipy.cluster.vq import kmeans # can identify up to 255 objects def mark_objects(image: Image.Image): new_image = image.copy() current = 0 free_labels = [] pixels = ...
3321101
from flask_wtf import FlaskForm from flask_wtf.file import FileField from flask_babel import lazy_gettext as _ from wtforms import StringField, SelectField, TextAreaField, DateField from wtforms.validators import InputRequired from app.forms.util import FieldVerticalSplit class CompanyForm(FlaskForm): name = Stri...
3321108
import csv import os.path import matplotlib import numpy as np from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size': 15}) n_trial = 10 top_k = 1 batch_size = 1000 max_step = np.inf max_reward = np.inf min_reward = -np.inf exp_name = 'CartpoleNd' exp_param = 'D1SUT5' extra_name = 'MCTS' prepa...
3321117
import json import six from functools import cmp_to_key from operator import itemgetter as ig from meetup.api import API_SERVICE_FILES OMIT_SERVICE = ['CreateBatch', 'Widget', 'WidgetQuery'] def cmp(a, b): return (a > b) - (a < b) def multikeysort(items, columns): comparers = [ ((ig(col[1:].strip(...
3321131
import aiohttp import asyncio import pytest from asynctest import CoroutineMock, patch from kutana import Kutana, Plugin, RequestException, Attachment from kutana.backends import Telegram from test_telegram_data import MESSAGES, UPDATES, ATTACHMENTS def test_no_token(): with pytest.raises(ValueError): Tel...
3321137
import csv import os import time from collections import Iterable from collections import OrderedDict import keras.backend as K import numpy as np import six from keras.callbacks import Callback from sklearn.model_selection import train_test_split def train_validate_test_split(df, train_percent=0.6, validate_percent...
3321140
import random # gives back an integer between 0 and 10 (inclusive) rand_int = random.randrange(11) print('I have thought of a number between 0 and 10.') print('Can you guess it within 4 attempts?\n') for _ in range(4): guess = int(input('Enter your guess: ')) if guess == rand_int: print('Wow, you gues...
3321176
import codecs import ipaddress import logging import random import socket import traceback from netaudio.dante.channel import DanteChannel from netaudio.dante.subscription import DanteSubscription from netaudio.dante.const import ( DEVICE_CONTROL_PORT, DEVICE_SETTINGS_PORT, FEATURE_VOLUME_UNSUPPORTED, ...
3321244
class Solution: def breakPalindrome(self, palindrome: str) -> str: """ :type palindrome: str :rtype: str """ for i in range(len(palindrome)): if palindrome[i] == 'a': continue if (i == int(len(palindrome) / 2)): continue...
3321245
from leapp.actors import Actor from leapp.exceptions import StopActorExecutionError from leapp.models import Report, KernelCmdline from leapp.tags import IPUWorkflowTag, ChecksPhaseTag from leapp import reporting class CheckFips(Actor): """ Inhibit upgrade if FIPS is detected as enabled. """ name = '...
3321247
import sys from getpass import getpass from requests import post from requests.exceptions import ConnectionError as ReqConError from .ip_checker import BaseUser, IPChecker, fh class DomainsUser(BaseUser): BASE_URL = "@domains.google.com/nic/update?hostname=" def __init__(self): super().__init__() ...
3321352
import numpy as np class Mass: def __init__(self, model): """ Defines the ShellProperties object. Parameters ---------- model : BDF the BDF object """ self.model = model self.n = 0 self.conm1 = model.conm1 self.conm2 = mode...
3321356
import json from app.common.datatypes import DataTypes from app.common.scoring_conf import ScoringMethods from config import Config __author__ = 'andreap' from flask import Flask, Response, current_app, request from flask_restful import fields import pprint class ResponseType(): JSON='json' XML='xml' TS...
3321377
import multiprocessing bind = "0.0.0.0:8000" workers = multiprocessing.cpu_count() * 2 + 1 errorlog = '/tmp/logs/gunicorn/access.log' loglevel = 'info' accesslog = '/tmp/logs/gunicorn/error.log' # UNCOMMENT BELOW IF USING SSL #secure_scheme_headers = {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FO...
3321394
import asyncio import bleak.backends.bluezdbus.defs as defs # type: ignore from typing import List, Any, Callable, Optional, Union from txdbus import client # type: ignore from txdbus.objects import DBusObject, RemoteDBusObject # type: ignore from bless.backends.bluezdbus.dbus.advertisement import ( # type: ign...
3321407
import sys class PingdomEmailReport(object): """Class represening a pingdom email report Attributes: * id -- Subscription identifier * name -- Subscription name * checkid -- Check identifier for check subscriptions * frequency -- Report frequency * additionalemails --...
3321413
from Tkinter import * import tkMessageBox from tkFileDialog import asksaveasfilename, askdirectory, askopenfilename from tkMessageBox import askokcancel import csv import os import json import webbrowser """ Author: <NAME> Credits: Elochukwu Ifediora C. """ class Template: def __init__(self, template=None): ...
3321492
import pytest import trafaret as t def test_dataerror_value(): error = t.DataError(error='Wait for good value', value='BAD ONE', code='bad_value') assert error.as_dict() == 'Wait for good value' assert error.as_dict(value=True) == "Wait for good value, got 'BAD ONE'" assert error.to_struct() == { ...
3321513
import time import cv2 from OCR.tf_tesseract.my_vgsl_model import ctc_loss, ctc_decode from OCR.ocr_utils import * from tensorflow.python.ops import state_ops from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import \ cudnn_rnn_canonical_to_opaque_params, CudnnLSTMSaveable def init(params, u...
3321517
import numpy as np import matplotlib.pyplot as plt import cv2 import random from skimage import measure import torch from torchvision import utils def make_numpy_grid(tensor_data): # tensor_data: b x c x h x w, [0, 1], tensor tensor_data = tensor_data.detach() vis = utils.make_grid(tensor_...
3321520
import os import tensorflow as tf from google.protobuf import text_format from tensorflow.python.client import timeline from tensorflow.python.profiler.option_builder import ProfileOptionBuilder def profile_report(sess, ops, feed_dict, out_dir, filename_prefix, filename_suffix): """ Creates a profile report....
3321534
class Trie: def __init__(self): self.size = 0 self.value = 0 self.letter_map = dict() def __repr__(self): return "{}: {}".format(self.letter_map, self.value) def add_word(self, word, value): if not word: self.value += value return let...
3321569
import os import sys import time from slidedeck.render import process_slides try: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler except: print('#'*78) print('The watch command requires that you install the python package "watchdog"') print('for monitoring...
3321592
from distutils.core import setup setup( name='pySchloss', version='0.2', packages=['pySchloss'], url='https://github.com/PJaros/pySchloss', license='Apache License, Version 2.0', author='<NAME>', author_email='<EMAIL>', description='Programm zum Schlosssystem im Ruum42', # See ...
3321613
import pytest from insights.parsers.pam import PamConf, PamDConf, PamConfEntry from insights.parsers import get_active_lines, pam from insights.tests import context_wrap import doctest PAM_CONF_DATA = """ #%PAM-1.0 vsftpd auth required pam_securetty.so vsftpd auth requisite pam_unix.so n...
3321635
from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, TypeVar, Union, cast, ) from devtools import debug from pydantic.main import BaseModel from pepperbot.exceptions import EmptySelectionException class ContextItem(BaseM...
3321654
import six from .node import Node @six.python_2_unicode_compatible class StockExchange(Node): """Represents a Website on CrunchBase""" KNOWN_PROPERTIES = [ 'name', 'short_name', 'symbol', 'created_at', 'updated_at', ] def __str__(self): return u'{name...
3321667
configfile: "config.yaml" import os import glob def get_ids_from_path_pattern(path_pattern): ids = sorted([os.path.basename(os.path.splitext(val)[0]) for val in (glob.glob(path_pattern))]) return ids # Make sure that final_bins/ folder contains all bins in single folder for binIDs # wildcar...
3321674
from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.faker import Faker c = ( Bar() .add_xaxis(Faker.choose()) .add_yaxis("商家A", Faker.values(), stack="stack1") .add_yaxis("商家B", Faker.values(), stack="stack1") .set_series_opts(label_opts=opts.LabelOpts(is_show=Fals...
3321677
import numpy as np import random,re from PIL import Image char_set=['7', 'p', 'w', 'n', '3', 'd', '6', 'b', '4', '2', 'g', 'a', 'c', '8', 'f', 'x', 'e', 'y', '5', 'm'] width, height, n_len, n_class = 100, 35, 6, len(char_set) def text2vec(text): text_len = len(text) if text_len > n_len: raise ValueEr...
3321682
import os import argparse import pandas as pd import xml.etree.ElementTree as ET def xml_to_csv(path): xml_list = [] for file in os.scandir(path): if file.is_file() and file.name.endswith(('.xml')): xml_file = os.path.join(path, file.name) tree = ET.parse(xml_file) ...
3321782
import pandas as pd import json ### get data from BarishNews telegram news server. It is daily number str_barishnews="{"+""""◽️تهران: 256 ◽️قم: 53 ◽️گیلان: 5 ◽️اصفهان: 170 ◽️البرز: 45 ◽️مازندران: 32 ◽️مرکزی: 31 ◽️قزوین: 27 ◽️سمنان: 63 ◽️گلستان: 9 ◽️خراسان رضوی: 34 ◽️فارس: 19 ◽️لرستان: 9 ◽️آذربایجان شرقی: 29 ◽️خوزستان: ...
3321818
from typing import Union import logging from multiprocessing import Process from pathlib import Path import shutil import time import daemon from filelock import FileLock import requests from .utils import API_URL, is_alive, load_json class Sender: """ Send logs to alchemy backend. """ _url = API_U...
3321887
import torch from torchvision import transforms import torch.nn as nn from model import ModelSpatial from dataset import GazeFollow from config import * from utils import imutils, evaluation import argparse import os from datetime import datetime import shutil import numpy as np from scipy.misc import imresize from t...
3321936
from typing import Tuple, List from clearml import Task import fire def with_ret() -> Tuple: print("With ret called") return 1, 2 def with_args(arg1: int, arg2: List): print("With args called", arg1, arg2) def with_args_and_ret(arg1: int, arg2: List) -> Tuple: print("With args and ret called", arg...
3321974
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Intprobemarker(Base): __slots__ = () _SDM_NAME = 'intprobemarker' _SDM_ATT_MAP = { 'HeaderPm': 'probemarker.header.pm-1', } def __init__(self, parent, list_op=False): super(Intprobemarker, self)....
3321991
import logging from typing import List from airflow_monitor.common import capture_monitor_exception from airflow_monitor.common.airflow_data import ( AirflowDagRun, AirflowDagRunsResponse, DagRunsStateData, ) from airflow_monitor.common.base_component import BaseMonitorComponent, start_syncer logger = l...
3322033
from click.testing import CliRunner from coreapi import Document, Link from coreapi.transports import HTTPTransport from coreapi_cli import __version__ as version from coreapi_cli.main import client, coerce_key_types import pytest import os import shutil import tempfile mock_response = None def set_response(doc): ...
3322065
from sqlalchemy import inspect from sqlalchemy.engine.reflection import Inspector from sqlmodel import create_engine def test_create_db_and_table(clear_sqlmodel): from docs_src.tutorial.create_db_and_table import tutorial003 as mod mod.sqlite_url = "sqlite://" mod.engine = create_engine(mod.sqlite_url) ...
3322069
from typing import List from datetime import timedelta from ebedke.utils import http from ebedke.pluginmanager import EbedkePlugin URL = "http://fruccola.hu/hu" API = "http://fruccola.hu/admin/api/daily_menu" def getMenu(today): date = today.strftime("%Y-%m-%d") out: List[str] = [] for place in http.get(...
3322096
import sys import gdb gdb.execute("file ./simple") gdb.execute("break main") gdb.execute("tbreak model_parameters::userfunction(void)") gdb.breakpoints() gdb.execute("run") gdb.execute("bt") class HelloWorld: def __init__ (self): self.name = "HelloWorld" print "Hello, World!" HelloWorld () gdb.execute("con...
3322114
from function import * from argparse import ArgumentParser from function import __doc__ as doc from sys import version_info , exit from os import popen if version_info[0] > 2: exit("Only Python2.7 is supported") ########### Arguements of the program ############## parser = ArgumentParser() parser.add_argument("-p", "...
3322138
GET_UNIQUE_ID = "SELECT nextval('audio_id_seq');" IS_EXIST = ( "select exists(select 1 from media_metadata_staging where raw_file_name= :file_name " "or media_hash_code = :hash_code);" ) COMMAND_WITH_LICENSE = ( "COPY media_metadata_staging(raw_file_name,duration,title," "speaker_name,audio_id,cleaned_d...
3322172
import torch from torch.utils.data import Dataset import random import numpy as np import h5py from model.hparam import hp class AMI_Dataset(Dataset): ''' This class is used to load and split the dataset in order to create batches (in parallel). (It inherits the torch.utils.data.Dataset class). In p...
3322180
import re import numpy as np import logging import time import io import sys import cv2 import pandas as pd from math import ceil from datetime import timedelta import os from utilities.pandas_loader import load_csv import cv2 def atoi(text): return int(text) if text.isdigit() else text def get_elapsed_time_and...
3322187
from __future__ import unicode_literals, division, print_function, absolute_import import os import matplotlib.pyplot as plt from datasets.cancer_papers.load_cancer import articles2dict from textcatvis.visualize_relevantwords import visualize_tfidf, visualize_distinctive, visualize_clf from textcatvis.check_query impor...
3322193
import numpy as np from c4.evaldiff import evaldiff from c4.engine.base import Engine from c4.evaluate import Evaluator, INF class GreedyEngine(Engine): def __init__(self): self._evaluator = Evaluator() self.evaluate = self._evaluator.evaluate def choose(self, board): moves = board.m...
3322200
import os from multiprocessing import cpu_count from pathlib import Path import pickle import re from PIL import Image import pandas as pd import numpy as np from sklearn.preprocessing import OneHotEncoder from sklearn.utils.class_weight import compute_class_weight from sklearn.model_selection import train_test_split ...
3322220
import numpy as np from PIL import Image from nets.srgan import build_generator from utils.utils import preprocess_input, cvtColor class SRGAN(object): #-----------------------------------------# # 注意修改model_path #-----------------------------------------# _defaults = { #-------...
3322227
import sys from pathlib import Path def check_if_available(prg, msg): """ Check if the given program is available. If not, then die with the given error message. """ if not Path(prg).is_file(): print(msg, file=sys.stderr) sys.exit(1)